Java的消费者/生产者
问题描述:
public class Queue {
int value = 0;
boolean isEmpty = true;
public synchronized void put(int n){
if (!isEmpty){
try {
System.out.println("producer is waiting");
wait();
}catch (Exception e){
e.printStackTrace();
}
}
value += n;
isEmpty = false;
System.out.println("The number of products:"+value);
notifyAll();
}
public synchronized void get(){
if (isEmpty){
try{
System.out.println("customer is waiting");
wait();
}catch (Exception e){
e.printStackTrace();
}
}
value --;
if(value<1){
isEmpty = true;
}
System.out.println("there are "+value+" left");
notifyAll();
}
}
public class Producer extends Thread{
private Queue queue;
public Producer(String name,Queue queue){
super(name);
this.queue = queue;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
queue.put(i+1);
}
}
}
public class Producer extends Thread{
private Queue queue;
public Producer(String name,Queue queue){
super(name);
this.queue = queue;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
queue.put(i+1);
}
}
}
public class Main {
public static void main(String[] args) {
Queue queue = new Queue();
Thread customer1 = new Customer("customer1",queue);
Thread producer1 = new Producer("producer1",queue);
customer1.setPriority(4);
producer1.setPriority(7);
producer1.start();
customer1.start();
}
}
输出:Java的消费者/生产者
The number of products:1 producer is waiting there are 0left customer is waiting The number of products:2 producer is waiting there are 1left there are 0left customer is waiting The number of products:3 producer is waiting there are 2left there are 1left there are 0left customer is waiting The number of products:4 producer is waiting there are 3left there are 2left there are 1left there are 0left customer is waiting The number of products:5 there are 4left there are 3left there are 2left there are 1left there are 0left customer is waiting
我不知道为什么的输出顺序是这样的。
为什么它不在输出像
The number of products:3 producer is waiting there are 2left The number of products: 6 there are 5left The number of products: 10 there are 9left The number of products: 15 there are 14left
答
的结果,我认为这个问题是你不beeing通知后,请检查你的病情。
你做
if (condition){
wait();
}
increment();
虽然你的线程可能会在别的方面得到通知,也不会检查,如果条件仍然存在,或由另一个线程已经解决,做增量反正。 正确的方法是在唤醒时重新检查您的状况,如:
while (condition){
wait();
}
increment();
为什么您需要多线程? – Professor901
我只是想知道为什么它不能这样工作。 –
过程同步不保证。 –