class Resources{
private int count = 0;
public synchronized void produce() {
if(count < 20) {
count++;
System.out.println(Thread.currentThread().getName() + ":开始生产第" + count + "个产品");
notify();
}else{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void consume() {
if(count > 0) {
System.out.println(Thread.currentThread().getName() + ":开始消费第"+ count + "个产品");
count--;
notify();
}else{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Producer extends Thread{
private Resources resource;
public Producer(Resources resource){
this.resource = resource;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":开始生产...");
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
resource.produce();
}
}
}
class Consumer extends Thread{
private Resources resource;
public Consumer(Resources resource){
this.resource = resource;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ":开始消费...");
while (true) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
resource.consume();
}
}
}
public class pv_Test {
public static void main(String[] args) {
Resources resource = new Resources();
Producer p = new Producer(resource);
p.setName("生产者");
Consumer v = new Consumer(resource);
v.setName("消费者");
p.start();
v.start();
}
}
操作系统之生产者-消费者
最新推荐文章于 2024-10-20 15:38:57 发布