2013-03-17 177 views
0
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 

計劃只得到困在這裏(不被終止)。

有人請解釋我在這裏做什麼錯?

+0

我可以說這是不是瞭解生產者/消費者問題的最佳途徑。 – 2013-03-17 17:59:21

+0

@AliAlamiri:好的。這個例子有什麼問題,請給我建議一些其他的東西。 – noone 2013-03-17 18:01:12

+0

這可能有助於http://java.dzone.com/articles/concurrency-pattern-producer – 2013-03-17 18:06:52

回答

1

聲明Value作爲volatile
即, static volatile boolean Value =false;
您已宣佈您的set/get方法​​。這意味着它們鎖定在this(該對象的固有鎖定)。
但在你的代碼實例爲每個線程,從而不同ThreadResource使他們​​因爲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)); 
+0

做到了這一點。同樣的結果 – noone 2013-03-17 17:58:32

+0

@AkshuJain:查看更新的答案 – Cratylus 2013-03-17 18:55:29

+0

明白了您的觀點謝謝! :)。我創建了兩個對象,併爲每個對象創建了兩個線程。所以基本上多線程的全部目的都失去了。 wait()方法正在等待一個沒有被任何其他線程共享的對象。 – noone 2013-03-18 05:51:36