2013-11-28 47 views
0

我有這個程序,其中兩個線程等待相同的鎖股票對象並導致程序掛起。但是Thread1不會爲Thread2鎖而放棄,反之亦然。如果這不是死鎖,這種情況叫什麼?死鎖是否需要兩個線程等待每個其他資源?

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

     Stock st = new Stock(); 
     Runnable p1 = new Producer(st); 
     Runnable c1 = new Consumer(st); 
     Thread t1 = new Thread(p1); 
     Thread t2 = new Thread(c1); 
     t1.start(); 
     t2.start(); 
    } 
} 

public class Producer implements Runnable{ 
    private final Stock st; 
    public Producer(Stock st) { 
     this.st=st; 
    } 
    @Override 
    public void run() { 
     try{ 
      while(true) 
       st.addStock(3); 
     } 
     catch(Exception e) 
     { 
      e.printStackTrace(); 
     } 
    } 
} 

public class Stock { 
    private int qoh; 
    public Stock() { 
    } 

    public synchronized int getStock(int required) throws InterruptedException 
    { 
     int take=0; 
     if(qoh> required) 
     { 
      qoh=qoh-required; 
      take=required; 
      //notify(); 
     } 
     else 
     { 
      wait(); 
     } 
     return take; 
    } 
    public synchronized void addStock(int stocks) throws InterruptedException 
    { 
     if(qoh >7) 
     { 
      wait(); 
     } 
     else 
     { 
      qoh=qoh+stocks; 
      System.out.println("Current Stock"+ qoh); 
     // notify(); 
     } 
    } 
    public int getorderLevel() 
    { 
     return this.qoh; 
    } 
} 

public class Consumer implements Runnable { 
    private final Stock st; 
    public Consumer(Stock st) { 
     this.st = st; 
    } 
    @Override 
    public void run() { 
     try { 
      while (true) { 
       int got = st.getStock(5); 
       System.out.println("Got =" + got); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+0

這是一個等待* * single *資源的兩個線程的例子,'Stock.'不是死鎖。 – EJP

+0

程序掛起,因爲你在run()中有一個無限循環 –

回答

相關問題