import java.util.Queue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
public class Application {
final static int TASKCOUNT = 20;
public static void main(String args[]) {
CountDownLatch locked = new CountDownLatch(TASKCOUNT);
Queue<Integer> queue = new LinkedBlockingQueue<>(TASKCOUNT);
Producer producer = new Producer(locked, queue, TASKCOUNT);
Consumer comsumer = new Consumer(locked, queue);
new Thread(producer).start();
new Thread(comsumer).start();
new Thread(comsumer).start();
System.out.println("主线程结束");
}
}
class Producer implements Runnable {
CountDownLatch locked;
Queue<Integer> queue;
int count;
public Producer(CountDownLatch locked, Queue<Integer> queue, int count) {
this.locked = locked;
this.queue = queue;
this.count = count;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
this.queue.add(i);
this.locked.countDown();
}
System.out.println(String.format("生产线程 %s 结束",Thread.currentThread().getId()));
}
}
class Consumer implements Runnable {
CountDownLatch locked;
Queue<Integer> queue;
public Consumer(CountDownLatch locked, Queue<Integer> queue) {
this.locked = locked;
this.queue = queue;
}
@Override
public void run() {
try {
this.locked.await();
while (true) {
if (this.queue.isEmpty()) {
break;
}
System.out.println(String.format("消费线程 ThreadId = %s, Task = %s ", Thread.currentThread().getId(), this.queue.poll()));
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(String.format("消费线程 %s 结束",Thread.currentThread().getId()));
}
}
}