本文主要是介绍多线程--SynchronousQueue,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
SynchronousQueue
同步队列。没有容量
写入一个元素,必须等待取出之后才可继续写入元素
Put之后必须take,才能继续put
public class Demo1 {public static void main(String[] args) {SynchronousQueue<String> synchronousQueue = new SynchronousQueue<String>();ExecutorService exec = Executors.newCachedThreadPool();exec.execute(new PutTask(synchronousQueue));exec.execute(new TakeTask(synchronousQueue));}
}class PutTask implements Runnable {SynchronousQueue synchronousQueue;PutTask(SynchronousQueue synchronousQueue) {this.synchronousQueue = synchronousQueue;}@Overridepublic void run() {try {System.out.println(Thread.currentThread().getName() + " put 1");synchronousQueue.put("1");System.out.println(Thread.currentThread().getName() + " put 2");synchronousQueue.put("2");System.out.println(Thread.currentThread().getName() + " put 3");synchronousQueue.put("3");} catch (InterruptedException e) {e.printStackTrace();}}
}class TakeTask implements Runnable {SynchronousQueue synchronousQueue;TakeTask(SynchronousQueue synchronousQueue) {this.synchronousQueue = synchronousQueue;}@Overridepublic void run() {try {System.out.println(Thread.currentThread().getName() + " take " + synchronousQueue.take());System.out.println(Thread.currentThread().getName() + " take " + synchronousQueue.take());System.out.println(Thread.currentThread().getName() + " take " + synchronousQueue.take());} catch (InterruptedException e) {e.printStackTrace();}}
}
这篇关于多线程--SynchronousQueue的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!