package com.gunshi; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.CountDownLatch; public class Tests extends Thread { static Queue queue = new LinkedList<>(); static int maxSize = 10; public static void main(String[] args) throws Exception { // Tests tc = new Tests(); // // 创建生产者线程 // Thread producer = new Thread(() -> { // try { // int value = 0; // while (true) { // tc.produce(); // Thread.sleep(2000); // 模拟生产耗时 // } // } catch (Exception e) { // Thread.currentThread().interrupt(); // } // }); // // // 创建消费者线程 // Thread consumer = new Thread(() -> { // try { // while (true) { // tc.customer(); // Thread.sleep(1500); // 模拟消费耗时 // } // } catch (Exception e) { // Thread.currentThread().interrupt(); // } // }); // // producer.start(); // consumer.start(); CountDownLatch countDownLatch = new CountDownLatch(3); for (int i = 0; i < 3; i++) { new Thread(() -> { System.out.println("执行任务中。。。"); try { Thread.sleep(1000); countDownLatch.countDown(); } catch (InterruptedException e) { throw new RuntimeException(e); } }).start(); } countDownLatch.await(); System.out.println("所有任务执行完毕"); } public synchronized void produce() throws Exception{ while (queue.size() == maxSize){ System.out.println("队列已满,生产者等待..."); wait(); } queue.offer(0); System.out.println("生产者生产。。" + "队列大小为:" + queue.size()); notifyAll(); } public synchronized void customer() throws Exception{ while(queue.size() == 0){ System.out.println("队列无数据,等待生产者生产"); wait(); } queue.poll(); System.out.println("消费者消费。。" + "队列大小为:" + queue.size()); notifyAll(); } }