Java并发包相关组件(2)
1. Exchanger
用于线程之间的数据交换
//生产者生产出固定的数量后与消费者的产品容器进行交换 class Producer implements Runnable{ private Queue<String> products; private Exchanger<Queue> exchanger; private int maxNum; private int id; private static int allId; public Producer(Queue<String> products,Exchanger exchanger,int maxNum) { this.products = products; this.exchanger = exchanger; this.maxNum = maxNum; this.id = allId++; } @Override public void run() { try { while (!Thread.interrupted()){ synchronized (Producer.class){ while (products.size() >= this.maxNum){ this.products = exchanger.exchange(products); } } System.out.println("生产者" + this.id + "号开始生产"); TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000) + 500); products.offer("产品-----" + "生产者" + this.id + "号"); System.out.println("生产者" + this.id + "生产完毕"); } } catch (Exception e){ e.printStackTrace(); } } } //消费者的产品队列为空的时候与生产者的产品队列进行交换 class Consumer implements Runnable{ private Queue<String> products; private Exchanger<Queue> exchanger; private int id; private static int allId; public Consumer(Queue<String> products,Exchanger exchanger) { this.products = products; this.exchanger = exchanger; this.id = allId++; } @Override public void run() { while (!Thread.interrupted()){ try { //保证只有一个线程会进行队列的交换 synchronized (Consumer.class){ while (products.isEmpty()){ exchanger.exchange(products); } System.out.println("消费者" + this.id + "开始消费" + products.poll()); } TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000) + 500); System.out.println("消费者" + this.id + "消费结束"); } catch (Exception e){ e.printStackTrace(); } } } } //main class Main{ public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(4); Queue<String> producerList = new LinkedList<>(); Queue<String> consumerList = new LinkedList<>(); Exchanger exchanger = new Exchanger(); for(int i = 0;i < 2;i++){ executorService.submit(new Producer(producerList,exchanger,5)); executorService.submit(new Consumer(consumerList,exchanger)); } } }