涉及线程的同步和通信
假设仓库中只存放一件产品,如果仓库中没有产品,则生产者将产品放入仓库,否则停止生产并等待,直到仓库中的产品被消费者取走为止,如果仓库中放有产品,则消费者可以将产品取走消费,否则停止消费并等待,直到仓库中再次放入产品为止。
//商品类
public class Product {
private String name;//名称 馒头 玉米饼
private String color;//颜色 白色 黄色
boolean flag = false;//默认没有商品
public Product() {}
public Product(String name, String color) { this.name = name; this.color = color; }
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public String getColor() {return color;}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Product{" +
"name='" + name + '\'' +
", color='" + color + '\'' +
'}';
}
}
//生产者线程
public class ProduceRunnable implements Runnable {
private Product product;
public ProduceRunnable() {}
public ProduceRunnable(Product product) { this.product = product; }
public void setProduct(Product product) {this.product = product;}
@Override
public void run() {
int i = 0;
while(true){
synchronized (product){
//1.如果已经有商品,就等待
if(product.flag){
try {
product.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//2. 生产商品并输出
if(i%2 ==0 ){
product.setName("馒头");
try {
Thread.sleep(10); //只释放cpu不释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
product.setColor("白色");
}else{
product.setName("玉米饼");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
product.setColor("黄色");
}
System.out.println("生产者生产一个商品:"+product.getName()+" "+product.getColor());
//3.改变商品有无的状态:有商品了
product.flag = true;
//4.通知消费
product.notify();//随机的唤醒一个线程(目前只有两个,被唤醒的肯定是消费者)
}
i++;
}
}
}
//消费者线程
public class ConsumeRunnable implements Runnable {
private Product product;
private Object obj = new Object();
public ConsumeRunnable() {}
public ConsumeRunnable(Product product) { this.product = product;}
public void setProduct(Product product) { this.product = product; }
@Override
public void run() {
while(true){
//对生产者加锁之后,也要对消费者加锁,并且必须是同一把锁!!!
synchronized (product){
//1.如果没有商品,就等待
if(!product.flag){
try {
product.wait(); //让出了cpu,也让出了锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//2.消费商品
System.out.println("消费者消费一个商品:"+product.getName()+" "+product.getColor());
//3.改变商品的有无状态:无
product.flag = false;
//4.通知生产者生产
product.notifyAll();//唤醒所有等待的线程(目前所有等待的线程只有一个,就是生产者)
}
}
}
}
//测试类
public class Test {
public static void main(String[] args) {
Product product = new Product();
//创建线程对象
Runnable runnable1 = new ProduceRunnable(product);
Thread thread1 = new Thread(runnable1);
ConsumeRunnable runnable2 = new ConsumeRunnable();
runnable2.setProduct(product);
Thread thread2 = new Thread(runnable2);
//启动线程
thread1.start();
thread2.start();
}
}
(生产一个,消费一个)运行如下
: