Java併發包相關元件(2)
阿新 • • 發佈:2021-06-29
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,intmaxNum) { 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)); } } }