package src.com.zhang.Thread;
/**
* 生产者和消费者问题
*/
class Clerk{
private int productCount=0;
public synchronized void produceProduct() {
if (productCount<20){
productCount++;
System.out.println(Thread.currentThread().getName()+"开始生产第"+productCount+"个产品");
notify();
}else {
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public synchronized void consumeProduct() {
if (productCount>0){
System.out.println(Thread.currentThread().getName()+"开始消费第"+productCount+"个产品");
productCount--;
notify();
}
else {
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
class Producer extends Thread{
private Clerk clerk;
public Producer(Clerk clerk){
this.clerk=clerk;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"开始生产...");
while (true){
try {
Thread.sleep(10);
clerk.produceProduct();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
class Consumer extends Thread{
private Clerk clerk;
public Consumer(Clerk clerk){
this.clerk=clerk;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"开始消费");
while (true){
try {
Thread.sleep(10);
clerk.consumeProduct();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
public class ProducersAndConsumers {
public static void main(String[] args) {
Clerk clerk=new Clerk();
Producer p1 = new Producer(clerk);
p1.setName("生产者1");
Consumer c1 = new Consumer(clerk);
c1.setName("消费者1");
p1.start();
c1.start();
}
}
java实现生产者和消费者问题
最新推荐文章于 2024-07-18 16:29:57 发布