生产者和消费者
程序员文章站
2022-07-12 17:41:49
...
package com.brendan.cn.pattern.produceConsumer;
public class Worker implements Runnable {
private Warehouse warehouse;
public Worker(Warehouse warehouse) {
this.warehouse = warehouse;
}
@Override
public void run() {
for (int i = 0; i <10 ; i++) {
warehouse.addTv(i+1);
}
}
}
package com.brendan.cn.pattern.produceConsumer;
public class Consumer implements Runnable {
private Warehouse warehouse;
public Consumer(Warehouse warehouse) {
this.warehouse = warehouse;
}
@Override
public void run() {
for (int i = 0; i <10 ; i++) {
warehouse.takeTv(i+1);
}
}
}
package com.brendan.cn.pattern.produceConsumer;
public class Warehouse {
private int count = 0 ;
synchronized public void addTv(int i) {
if(count == 4){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count ++;
System.out.println("生产了编号为"+i+"的电视机, "+" 库存为"+count);
this.notify();
}
synchronized public void takeTv(int i) {
if(count <= 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count --;
System.out.println("消费了编号为"+i+"的电视机, "+" 库存为"+count);
this.notify();
}
}
package com.brendan.cn.pattern.produceConsumer;
public class TestPC {
public static void main(String[] args) {
Warehouse warehouse = new Warehouse();
new Thread(new Worker(warehouse)).start();
new Thread(new Consumer(warehouse)).start();
}
}