标签:
package Thread; import java.util.Random; import java.util.concurrent.Exchanger; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ExchangerTest { public static void main(String[] args) { ExecutorService executorService=Executors.newCachedThreadPool(); final Exchanger<String> exchanger=new Exchanger<String>(); executorService.execute(new RunnableTest("A",exchanger)); executorService.execute(new RunnableTest("B",exchanger)); } } class RunnableTest implements Runnable{ private String data; private Exchanger<String> exchanger; public RunnableTest(String data,Exchanger<String> exchanger){ this.data=data; this.exchanger=exchanger; } @Override public void run() { try { System.out.println(Thread.currentThread().getName()+" data:"+data); Thread.sleep(new Random().nextInt(1000)); String swapData=exchanger.exchange(data); System.out.println(Thread.currentThread().getName() +"have swap data "+swapData); } catch (InterruptedException e) { e.printStackTrace(); } } }
注意使用阻塞队列其本身的方法
put方法用来向队尾存入元素,如果队列满,则等待;
take方法用来从队首取元素,如果队列为空,则等待;
offer方法用来向队尾存入元素,如果队列满,则等待一定的时间,当时间期限达到时,如果还没有插入成功,则返回false;否则返回true;
poll方法用来从队首取元素,如果队列空,则等待一定的时间,当时间期限达到时,如果取到,则返回null;否则返回取得的元素;
Java多线程与并发库高级应用 学习笔记 16-22课 +面试题
标签:
原文地址:http://www.cnblogs.com/linkarl/p/4823878.html