0
package ProducerConsumer;

public class Queue {

    int item;
    boolean isEmpty=false;

    public int put(int item)
    {
        this.item=item;
        return this.item;
    }

    public int get()
    {
        return item;
    }

}

package ProducerConsumer;

public class Producer extends Thread{


    Queue q;
    public Producer(Queue q)
    {
        this.q=q;
    }

    @Override
    public void run() {

        synchronized (q) {

            for(int i=1;i<=5;i++)
            {
                if(q.isEmpty==false)
                    try {
                        q.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                System.out.println("Producer produced = "+q.put(i));
                q.isEmpty=false;
                q.notify();
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }


        }
    }

}

package ProducerConsumer;

public class Consumer extends Thread {

    Queue q;
    public Consumer(Queue q)
    {
        this.q=q;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        synchronized (q) {
            for(int i=1;i<=5;i++)
            {
                if(q.isEmpty==true)
                    try {
                        q.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    System.out.println("ITEM CONSUMED:"+q.get());
                    q.isEmpty=true;
                    q.notify();

            }
        }
    }

}

package ProducerConsumer;

public class MainApp {
    public static void main(String[] args)

    {
        Queue q=new Queue();

        Thread t1=new Thread(new Producer(q));
                //t1.setPriority(1);
        t1.start();

        Thread t2=new Thread(new Consumer(q));
        t2.start();



    }
}

This is my output:

ITEM CONSUMED:0
Producer produced = 1
ITEM CONSUMED:1
Producer produced = 2
ITEM CONSUMED:2
Producer produced = 3
ITEM CONSUMED:3
Producer produced = 4
ITEM CONSUMED:4
Producer produced = 5

Question is: why my consumer thread is running first ? I tried setting the priority for my Producer thread also. Its not working. Also, if there is any other flaw in the code or design flaw in code, please do mention.

4

2 回答 2

1
synchronized (q) {

You told all of your threads to never run at the same time.
That defeats the purpose of threads.

于 2013-10-06T18:31:54.247 回答
0

线程的并行执行意味着它们可以以任何顺序运行。如果您希望它们以预定义的顺序运行,则必须明确编程。线程的启动顺序并不是设置线程执行顺序的意思。

于 2013-10-06T19:47:22.883 回答