青萍之末一缕风 2016-11-24 10:11 采纳率: 0%
浏览 990

我写的一个消费者生产者模型,出了点问题,大家帮我分析一下。

public class test {

public static void main(String[] args) {
    productor productor=new productor();
    ProductThread productThread=new ProductThread(productor);
    ConsumerThread consumerThread=new ConsumerThread(productor);

    Thread[] product=new Thread[10];
    Thread[] consumer=new Thread[10];
    for (int i = 0; i <10 ; i++) {
        product[i]=new Thread(productThread,"生产者"+i);
        product[i].start();
        consumer[i]=new Thread(consumerThread,"消费者"+i);
        consumer[i].start();
    }
}

}
class productor{
public final int MAX_COUNT=10;
public volatile int count=0;
public void read()
{
count--;
System.out.println(Thread.currentThread().getName()+"消费了一个产品");
System.out.println("当前产品数量为:"+count);
}
public void write()
{
count++;
System.out.println(Thread.currentThread().getName()+"生产了一个产品");
System.out.println("当前产品数量为:"+count);
}
}
//消费者线程
class ConsumerThread implements Runnable{
private productor productor;
public ConsumerThread(productor productor)
{
this.productor=productor;
}
public void run()
{
while (true)
{
while (productor.count {
try {
System.out.println(Thread.currentThread().getName()+"表示产品并不够消费,我去睡会");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (productor)
{
try {
productor.read();
// Thread.sleep(1000);
productor.notify();
productor.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
//生产者线程
class ProductThread implements Runnable{
private productor productor;
public ProductThread(productor productor)
{
this.productor=productor;
}
public void run(){
while (true)
{
while (productor.count>=productor.MAX_COUNT)
{
try {
System.out.println(Thread.currentThread().getName()+"表示产品都特么的满了,我去睡会");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (productor)
{
try {
productor.write();
productor.notify();
productor.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
这是我写的生产者消费者模型,分别在生产者消费者线程中对产品的上限和下限进行了判断,但是还是出现了异常的结果。如图:图片说明
其余时刻都正常,大神帮忙看看哪里错了,错在什么地方

  • 写回答

1条回答 默认 最新

  • qq_36522073 2016-11-24 12:06
    关注

    用个线程池或者同步锁试下

    评论

报告相同问题?

悬赏问题

  • ¥15 如何修改pca中的feature函数
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法