一个线程从队列里取数据,一个线程往队列里添加数据
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 service = Executors.newCachedThreadPool(); final Exchanger<String> exchanger = new Exchanger<String>(); service.execute(new Runnable() { @Override public void run() { try { String data1 = "zxx"; System.out.println("线程" + Thread.currentThread().getName() + "正在把数据" + data1 + "换出去"); Thread.sleep((long) Math.random() * 10000); String data2=(String) exchanger.exchange(data1); System.out.println("线程" + Thread.currentThread().getName() + "换回的数据为" + data2); } catch (Exception e) { e.printStackTrace(); } } }); service.execute(new Runnable() { @Override public void run() { try { String data1 = "lhm"; System.out.println("线程" + Thread.currentThread().getName() + "正在把数据" + data1 + "换出去"); Thread.sleep((long) Math.random() * 10000); String data2=(String) exchanger.exchange(data1); System.out.println("线程" + Thread.currentThread().getName() + "换回的数据为" + data2); } catch (Exception e) { e.printStackTrace(); } } }); } }
长度为1的阻塞队列实现同步通知
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class BlockingQueueCondition { public static void main(String[] args) { ExecutorService service = Executors.newSingleThreadExecutor(); final Business3 business = new Business3(); service.execute(new Runnable(){ public void run() { for(int i=0;i<50;i++){ business.sub(); } } }); for(int i=0;i<50;i++){ business.main(); } } } class Business3{ BlockingQueue<Integer> subQueue = new ArrayBlockingQueue<Integer>(1); BlockingQueue<Integer> mainQueue = new ArrayBlockingQueue<Integer>(1); //这里是匿名构造方法,只要new一个对象都会调用这个匿名构造方法,它与静态块不同,静态块只会执行一次, //在类第一次加载到JVM的时候执行 //这里主要是让main线程首先put一个,就有东西可以取,如果不加这个匿名构造方法put一个的话程序就死锁了 { try { mainQueue.put(1); } catch (InterruptedException e) { e.printStackTrace(); } } public void sub(){ try { mainQueue.take(); for(int i=0;i<10;i++){ System.out.println(Thread.currentThread().getName() + " : " + i); } subQueue.put(1); }catch(Exception e){ } } public void main(){ try { subQueue.take(); for(int i=0;i<5;i++){ System.out.println(Thread.currentThread().getName() + " : " + i); } mainQueue.put(1); }catch(Exception e){ } } }
本文出自 “点滴积累” 博客,请务必保留此出处http://tianxingzhe.blog.51cto.com/3390077/1716903