【问题标题】:Java consumer/producerJava 消费者/生产者
【发布时间】:2017-08-08 13:45:54
【问题描述】:
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();

    }

}

输出:

产品数量:1 生产者在等待 还有0left 客户在等待 产品数量:2 生产者在等待 有 1 个 还有0left 客户在等待 产品数量:3 生产者在等待 有2个 有 1 个 还有0left 客户在等待 产品数量:4 生产者在等待 有3个 有2个 有 1 个 还有0left 客户在等待 产品数量:5 有4个 有3个 有2个 有 1 个 还有0left 客户在等待

我不知道为什么输出的顺序是这样的。

为什么不像

那样输出结果 产品数量:3 生产者在等待 有2个 产品数量:6 有5个 产品数量:10 剩下9个 产品数量:15 还有14个

【问题讨论】:

  • 为什么需要多线程?
  • 我只是想知道为什么它不能这样工作。
  • 无法保证进程同步。
  • 总是输出一样的东西,顺序没有变化。
  • 您的生产者将 15 个“项目”放入队列中。这是你的意图吗?

标签: java multithreading


【解决方案1】:

我认为问题在于您在收到通知后没有检查您的状况。

你做一个

if (condition){
  wait();
}
increment();

虽然可以从另一个上下文通知您的线程,但它不会检查条件是否仍然存在或已被另一个线程解决,并且无论如何都会执行增量。 正确的做法是在醒来时重新检查您的状况,例如:

while (condition){
  wait();
}
increment();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多