2017-12-15 25 views
0

Oracle Java 문서 (https://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html)에 제공된 교착 상태 예제의 행을 따라, 나는 자국에서 상황을 시뮬레이션하려고했습니다. 한 쌍의 기차가 반대 방향으로 달릴 때, 중계국에 도착하는 열차는 대기중인 직원에게 "열쇠"를 먼저줍니다. 열차는 멈추지 않지만 엔진 드라이버는 열쇠가있는 큰 주머니를 플랫폼에 던집니다. 거기에서 기다리고있는 직원은 그것을 모을 것이다). 나중에 다른 기차가 중계국에 도달하여 수집됩니다. 두 열차가 동시에 역에 도착하면 교착 상태가됩니다. 내가 좋아하는 출력을 기다리고 있었다이 Java 프로그램은 예상 교착 상태를 표시하지 않습니다.

public class Deadlock 
{ 
    static class Express 
    { 
     private final String name; 
     public Express(String name) 
     { 
      this.name = name; 
     } 
     public String getName() 
     { 
      return this.name; 
     } 
     public synchronized void reached(Express laterTrain) 
     { 
      System.out.println(this.name + " is earlier than " + 
       laterTrain.getName()); 
      giveKey(laterTrain); 
     } 
     public synchronized void giveKey(Express laterTrain) 
     { 
      System.out.println(name + " gives key to " + 
       laterTrain.getName()); 
     } 
    } 
    public static void main(String[] args) 
    { 
     final Express Rajdhani1 = new Express("Rajdhani ONE"); 
     final Express Rajdhani2 = new Express("Rajdhani TWO"); 
     new Thread(new Runnable() 
     { 
      public void run() 
      { 
       Rajdhani1.reached(Rajdhani2); 
      } 
     }).start(); 
     new Thread(new Runnable() 
     { 
      public void run() 
      { 
       Rajdhani2.reached(Rajdhani1); 
      } 
     }).start(); 
    } 
} 

:

Rajdhani ONE is earlier than Rajdhani TWO 
Rajdhani TWO is earlier than Rajdhani ONE 

영원히 거기에 매달려 프로그램 그래서, 나는 이것을 설명하기 위해 다음 코드를 썼다. 하지만 다음과 같은 결과가 나왔고 실행이 즉시 커맨드 라인으로 돌아 왔습니다. 방법?

Rajdhani ONE is earlier than Rajdhani TWO 
Rajdhani TWO is earlier than Rajdhani ONE 
Rajdhani ONE gives key to Rajdhani TWO 
Rajdhani TWO gives key to Rajdhani ONE 

답변

1

난 당신의 코드를 실행하지 않은,하지만 당신은 연결된 예제 코드에서 다르게 일을하고있다 : 당신이 reached() 함수에서 잘못된 개체에 giveKey을 요구하고있다.

는 참조 예에 따르면 그것은해야한다 :

// bower.bowBack(this); 
laterTrain.giveKey(this); 

하지만 당신은 요구하고있다 : 당신이 giveKey 메소드를 호출 할 때

// this.bowBack(bower); 
this.giveKey(laterTrain); 
+0

하울러를 지적 해 주셔서 감사합니다. 나는 당신의 교정을 적용하고 그것은 예상대로 작동합니다. –

0

은 그 방법에 다른 객체를 전달합니다. 메서드가 호출되는 객체를 전달하면 안됩니까?

giveKey 함수에 "this"를 전달하고 출력을 체크 아웃해야합니다. 그것은 당신이 제공 한 문서 링크마다 작동해야합니다.