Creator.java
public class Creator implements Runnable {
private Queue<String> queue;
private Set<Thread> creators;
public Creator(Queue<String> queue, Set<Thread> creators) {
this.queue = queue;
this.creators = creators;
}
@Override
public void run() {
creators.add(Thread.currentThread());
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("生产了一个商品");
queue.add(String.format("%s 第%02d件商品", Thread.currentThread().getName(), i));
synchronized (queue) {
queue.notifyAll();
}
}
creators.remove(Thread.currentThread());
synchronized (queue) {//此处添加线程锁是为了判断当所有生产者全部完成任务后,唤醒消费者进行判断,从而结束线程。
queue.notifyAll();
}
}
}
Customer.java
public class Customer implements Runnable {
private Queue<String> queue;
private Set<Thread> creators;
public Customer(Queue<String> queue, Set<Thread> creators) {
this.queue = queue;
this.creators = creators;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (queue) {
if (queue.isEmpty()) {//queue相当于仓库,creators相当工厂里的工人,当仓库为空并且工厂里的工人为空时,线程结束运行。
if (creators.isEmpty()) {
break;
} else {
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
System.out.println("消费:" + queue.poll());
}
}
}
}
}
main函数
public class Test02 {
public static void main(String[] args) {
Queue<String> queue = new ArrayDeque<>();
Set<Thread> creators = new HashSet<>();
Creator creator = new Creator(queue, creators);
Customer customer = new Customer(queue, creators);
new Thread(creator, "生产者 1").start();
new Thread(creator, "生产者 2").start();
new Thread(creator, "生产者 3").start();
while (creators.isEmpty()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
new Thread(customer).start();
new Thread(customer).start();
new Thread(customer).start();
new Thread(customer).start();
new Thread(customer).start();
}
}