java--线程生产消费者问题

产品苹果类

package producter_consumer;

public class Apple {
private int num=0;

public void setNum(int num){
this.num=num;
}
public int getNum(){
return num;
}
//生产苹果产品
public synchronized void produce(){
num++;
System.out.println("生产了一个苹果,现在数量为:"+num);
this.notifyAll();
}
//消费苹果产品
public synchronized void consume(){
num--;
System.out.println("消费了一个苹果,现在数量为:"+num);
this.notifyAll();
}
//此方法根据当前的苹果数量来判断是否应该生产苹果产品
public synchronized void waitForProduce() {
while(num<1){
System.out.println("等待生产中...");
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//此方法根据当前的苹果数量来判断是否能够消费苹果产品
public synchronized void waitForConsume(){
while(num>10){
System.out.println("等待消费中...");
try {
this.wait();
} catch (InterruptedException e) {

e.printStackTrace();
}
}
}
}



<--------------------------可爱的分割线------------------------------->
生产类

package producter_consumer;

import java.lang.Thread;

public class Produce implements Runnable{

Apple apple=null;

public Produce(Apple ap){
this.apple=ap;
}

public void run() {
int m=20;
try {
while(m>0){

Thread.sleep(1000);
apple.waitForConsume();
System.out.println("正在准备生产...");
apple.produce();
System.out.println("现在苹果数量为:"+apple.getNum());

m--;
}
} catch (InterruptedException e) {

e.printStackTrace();
}


}

}



<--------------------------可爱的分割线------------------------------->
消费类


package producter_consumer;

import java.lang.Thread;

public class Consume implements Runnable {

Apple apple=null;

public Consume(Apple ap){
this.apple=ap;
}

public void run() {
int m=20;
try {
while(m>0){

Thread.sleep(5000);
apple.waitForProduce();
System.out.println("正在准备消费...");
apple.consume();
System.out.println("现在苹果数量为:"+apple.getNum());
m--;
}
} catch (InterruptedException e) {

e.printStackTrace();
}

}

}



<--------------------------可爱的分割线------------------------------->
生产消费测试类



package producter_consumer;

import java.lang.Thread;

public class PCTest {


public static void main(String[] args) throws InterruptedException {
Apple apple=new Apple();
Produce p=new Produce(apple);
Consume c=new Consume(apple);

new Thread(p).start();
new Thread(c).start();

Thread.sleep(10000);
//安全退出
//System.exit(0);
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值