멀티 스레드 시나리오에서 Deadlock을 설명하는 Oracle의 Java 자습서에서이 example을 발견했습니다. System.out.format 및 System.out.println을 이용한 스레딩
그래서이 예제에서 나는Alphonse: Gaston has bowed to me!
Gaston: Alphonse has bowed back to me!
Gaston: Alphonse has bowed to me!
Alphonse: Gaston has bowed back to me!
그래서 출력 다음 줄 17에서 변화와 이러한 변화를 교착 상태를 발생시키지 않고 성공적으로 종료 프로그램을 수행하면 라인 (18)
public class DeadLock {
static class Friend {
private final String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public synchronized void bow(Friend bower) {
//My Changes
//System.out.format("%s: %s" + " has bowed to me!%n", this.name, bower.getName()); //Line 17
System.out.println(this.name + ": " + bower.getName() + " has bowed to me!"); //Line 18
bower.bowBack(this);
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s" + " has bowed back to me!%n", this.name, bower.getName());
}
}
public static void main(String[] args) {
final Friend alphonse = new Friend("Alphonse");
final Friend gaston = new Friend("Gaston");
new Thread(new Runnable() {
@Override
public void run() {
alphonse.bow(gaston);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
gaston.bow(alphonse);
}
}).start();
}
}
다음 제작 및 인쇄 내 질문 - 왜 이런 행동을 했습니까? println 문은 교착 상태를 어떻게 막았습니까?
어떻게 될지 모르겠습니다. 'System.out.format'은 잠금과 관련하여'System.out.println'과 다른 것을 실제로하지 않습니다. –
아무런 차이가 없습니다. 스레드 인터리빙에 따라 교착 상태가 달라 지므로 실행간에 차이가납니다. System.format을 사용하여 여러 번 실행하면 때때로 정확한 결과를 볼 수 있습니다. 그리고 println을 사용하면 프로그램이 교착 상태에있는 곳에서도 실행을 볼 수 있습니다. – assylias
사실 : 첫 번째 변종은 [ideone에서 잘 돌아갈 수 있습니다] (http://ideone.com/bV6nd8). –