Java中Producer Consumer的实现有什么问题?

时间:2015-06-14 19:18:45

标签: java multithreading

我使用共享缓冲区类实现了经典的生产者/消费者问题。

由于某种原因,我没有得到正确的输出序列。

我已经尝试了很多次,但是没有发现这个漏洞,有人可以指出这个错误吗?

public class BufferProdCons {

    boolean produced = false;

    int data;

    public synchronized void produceData(int d) {

        while (produced) {

            try {
                wait();
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            }
        }

    //  System.out.println("data produced");
        data = d;
        produced = true;
        this.notify();
    }

    public synchronized int consumeData() {
        while (!produced) {

            try {
                wait();
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            }
        }

    //  System.out.println("data consumed");
        int d =data;
        produced = false;
        this.notify();
        return d;
    }
}

public class Consumer extends Thread {

    BufferProdCons buffer ;
    Consumer(BufferProdCons buf){
        buffer =  buf;
    }


    public void run(){
        for (int i =0;i<10;i++){
            int d=buffer.consumeData();
            System.out.println("Consumed data "+d);
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

public class Producer extends Thread {

    BufferProdCons buffer;

    Producer(BufferProdCons buf){
        buffer = buf;
    }

    @Override
    public void run(){
        for(int i=0;i<10;i++){
            System.out.println("Produced "+i);
            buffer.produceData(i);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

public class MainProdCons {

    public static void main(String[] args) {


        BufferProdCons  buffer = new BufferProdCons();

        Thread t1 = new Producer(buffer);
        Thread t2 = new Consumer(buffer);

        t1.start();t2.start();
    }

}

示例输出

Produced 0
Consumed data 0
Produced 1
Consumed data 1
Produced 2
Produced 3
Consumed data 2
Produced 4
Consumed data 3
Produced 5
Consumed data 4
Produced 6
Consumed data 5
Produced 7
Consumed data 6
Produced 8
Consumed data 7
Produced 9
Consumed data 8
Consumed data 9

我的理解是,生产者和消费者行的顺序应该是交替的,但正如你所看到的,它们有时会连续出现。

0 个答案:

没有答案