2013-11-28 1 views
0

두 개의 스레드가 동일한 잠금 Stock Object를 기다리고 프로그램을 중단시키는이 프로그램이 있습니다. 그러나 Thread1은 Thread2 잠금에 대해 waiing하지 않으며 반대의 경우도 마찬가지입니다. 이것이 교착 상태가 아니라면이 상황은 무엇이라고 불 립니 까?교착 상태에 서로 다른 자원을 기다리는 두 개의 스레드가 필요합니까?

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()에 무한 루프가 있기 때문에 프로그램이 중단됩니다. –

답변

0

당신은 올바른 :이 교착 상태의 예 아닙니다.
의 형태 인 synchronization의 예입니다.
Java에서 생산자/소비자 문제는 종종 BlockingQueue을 사용하여 해결됩니다.