生产者消费者中的死锁

时间:2013-03-17 17:48:42

标签: java consumer producer

    I have following classes :

    package com.akshu.multithreading;

    public class ThreadResource {

        static int a;
     static boolean Value =false;
        public synchronized int getA() {
            while(Value == false){
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            Value= false;
            notify();


            return a;
        }

        public synchronized void setA(int a) {
            while(Value == true)
            {
                try {
                    wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            ThreadResource.a = a;
            Value=true;
            notify();

        }


    }


    ------------------


    /**
     * 
     */
    package com.akshu.multithreading;

    /**
     * @author akshu
     *
     */
    public class MyThreadA implements Runnable  {

        int a = 0;
        ThreadResource tR= new ThreadResource();

        @Override
        public void run() {


        for (int i = 0; i < 15; i++) {



            tR.setA(++a);
            System.out.println(" value of a :"+a);





        }

        }
    }

    ------------

    package com.akshu.multithreading;

    public class MyThreadB implements Runnable {

        @Override
    public void run() {
        // TODO Auto-generated method stub
        ThreadResource tR =new ThreadResource();
        for (int i = 0; i < 15; i++) {

        System.out.println("getA()"+tR.getA());

                }
    }
    }
    ----

    package com.akshu.multithreading;

    public class ThreadExecutionPoint {

        public static void main(String args[])  {

            Thread th1 = new Thread(new MyThreadA());
            Thread th2 = new Thread(new MyThreadB());

            th1.start();
            th2.start();
        }
    }

我试图通过上面的代码了解生产者消费者问题。当我执行上面的代码时,我正在

    value of a :1
    getA()1

程序只会卡在这里(不要终止)。

有人请解释我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

Value声明为volatile
static volatile boolean Value =false;
您已声明set/get方法synchronized。这意味着它们锁定在this(对象的内部锁定) 但是在您的代码中,您为每个帖子实例化了不同的ThreadResource,从而使它们成为synchronized,因为this对于每种情况都不同。
按如下方式更改您的代码:

public class MyThreadA implements Runnable {  
    ThreadResource tR;  

     public MyThreadA(ThreadResource tr) {  
        this.tR = tr;  
    }  
// your run method here NOT declaring a ThreadResource anymore!!!
}   

MyThreadB

相同

然后在ThreadExecutionPoint

ThreadResource tr = new ThreadResource();  
Thread th1 = new Thread(new MyThreadA(tr));  
Thread th2 = new Thread(new MyThreadB(tr));