Java多线程,消费问题,下面代码问题在哪里
编写生产者消费者多线程程序,设有一个最大库存量为4的电视机仓库,生产10台电视机,一边生产一边销售(消费)。
public class Custom {
private int num = 0;
private int count;
public static void main(String[] args) {
Custom custom = new Custom();
Dc dc = custom.new Dc();
Ec ec = custom.new Ec();
Thread thread = new Thread(dc);
Thread thread1 = new Thread(ec);
thread.setName("生产电视:");
thread1.setName("销售1台电视,仓库还有:");
thread.start();
thread1.start();
}
class Dc implements Runnable {
@Override
public void run() {
show();
}
private synchronized void show() {
boolean flag = true;
while (flag) {
if (num > 3) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
num++;
System.out.println(Thread.currentThread().getName() + num + "台");
count++;
if (count == 10) {
flag = false;
}
notifyAll();
}
}
}
class Ec implements Runnable {
private synchronized void show(){
while (true) {
if (num < 1) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
num--;
System.out.println(Thread.currentThread().getName() + num + "台");
notifyAll();
}
}
@Override
public void run() {
show();
}
}
}