案列:当生产者生产的东西超过10个时,就等待。等待消费者消费,当没有产品的时候,消费者就等待,唤醒生产者,让生产者继续生产。
代码块:
package cn.TeacherXu;
import java.util.concurrent.LinkedBlockingQueue;
public class Test0 {
public static void main(String[] args) {
LinkedBlockingQueue<Apple2> queue = new LinkedBlockingQueue<>();
Producer2 p = new Producer2(queue);
new Thread(p,"生产者1").start();
new Thread(p,"生产者2").start();
new Thread(p,"生产者3").start();
Consumer2 c = new Consumer2(queue);
new Thread(c,"消费者1").start();
new Thread(c,"消费者2").start();
new Thread(c,"消费者3").start();
}
}
class Apple2 {
private String name;
private int age;
public Apple2() {
}
public Apple2(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "[name=" + name + ", age=" + age + "]";
}
}
class Producer2 implements Runnable {
private LinkedBlockingQueue<Apple2> queue;
public Producer2(LinkedBlockingQueue<Apple2> queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
synchronized (queue) {
while (queue.size() > 10) {
try {
queue.notifyAll();
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Apple2 a = new Apple2("APPLE", 500);
queue.add(a);
System.out.println(Thread.currentThread().getName() + "生产" + a.getName());
queue.notifyAll();
}
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
class Consumer2 implements Runnable {
private LinkedBlockingQueue<Apple2> queue;
public Consumer2(LinkedBlockingQueue<Apple2> queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
synchronized (queue) {
while (queue.size() == 0) {
try {
queue.notifyAll();
queue.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
Apple2 a = queue.take();
System.out.println(Thread.currentThread().getName() + "消费了"+a.getName());
queue.notifyAll();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}