这篇文章给大家介绍java中怎么使用BlockingQueue阻塞队列实现互斥同步通信,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
package com.study; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class BlockingQueueDemo { public static void main(String[] args) { BlockingQueueDemo blockingQueueDemo = new BlockingQueueDemo(); final BlockingQueueClass blockingQueueClass = blockingQueueDemo.new BlockingQueueClass(); Thread thread = new Thread(new Runnable() { @Override public void run() { while (true) { blockingQueueClass.put(); } } }); thread.start(); Thread thread2 = new Thread(new Runnable() { @Override public void run() { while (true) { blockingQueueClass.take(); } } }); thread2.start(); } class BlockingQueueClass{ BlockingQueue<Integer> takeblockingQueue = new ArrayBlockingQueue<Integer>(1); BlockingQueue<Integer> putblockingQueue = new ArrayBlockingQueue<Integer>(1); { try { takeblockingQueue.put(1); } catch (InterruptedException e) { e.printStackTrace(); } } public void put(){ try { putblockingQueue.put(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("put..."); try { takeblockingQueue.take(); } catch (InterruptedException e) { e.printStackTrace(); } } public void take(){ try { takeblockingQueue.put(1); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("take..."); try { putblockingQueue.take(); } catch (InterruptedException e) { e.printStackTrace(); } } } }
关于java中怎么使用BlockingQueue阻塞队列实现互斥同步通信就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。