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();
}
}
}
}
}
这是我写的生产者消费者模型,分别在生产者消费者线程中对产品的上限和下限进行了判断,但是还是出现了异常的结果。如图:
其余时刻都正常,大神帮忙看看哪里错了,错在什么地方