青萍之末一缕风 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
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM