2013-09-02 2 views
0

아래 코드를 실행하려고하면 코드가 wait()가있는 블록이나 notifyAll()이있는 블록에 입력되지 않습니다. 그러나 프로그램의 결과는 "A B"또는 "B A"입니다. 나는 프로그램에서 빠진 것이 무엇인지 이해하지 못한다.대기 및 알림 프로그램을 올바르게 해석 할 수 없습니다.

public class threads1 extends Thread { 

    static Object obj = new Object(); 

    public threads1(String str) { 
     super(str); 
    } 

    public void run() { 
     try { 
      waitforsignal(); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    public void waitforsignal() throws InterruptedException { 

     synchronized (obj) { 
      System.out.println(Thread.currentThread().getName()); 
      while (Thread.currentThread().getName() == "A") { 
       System.out.println("into wait"); 
       obj.wait(); 
      } 
      if ((Thread.currentThread().getName() == "B")) { 
       System.out.println("had notified"); 
       obj.notifyAll(); 
      } 
     } 
    } 

    public static void main(String... strings) throws InterruptedException { 
     Thread t1 = new threads1("A"); 
     Thread t2 = new threads1("B"); 
     t1.start(); 
     t2.start(); 
    } 
} 

답변

1

스레드와 아무런 관련이 없습니다. you are comparing strings with == instead of equals. ...

Thread.currentThread().getName().equals("A") 

는 항상 프로그램이 완료되지 않습니다, 사실이 될 것이다

+0

을 그리고()는 Thread.currentThread되지 않습니다 :

당신이 것을 해결 한 후, 실 t1에 대한 점에 유의. getName()은 문자열을 생성합니다. 다른 참조에서 생성 된 문자열 객체가 항상 풀의 동일한 문자열 참조를 가리키기 때문에 ==를 사용할 수없는 이유는 무엇입니까? – smslce

+0

모든 문자열은 여기서 컴파일 타임 상수이기 때문에 문자열 인턴하기 때문에 이것이 문제라고 생각하지 않습니다. –

+1

@TedHopp,'Thread'의 impl을 알지 못해서 그 가정을 할 수있을 지 확신하지 못합니다. 실제로 여기에 http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Thread.java#Thread.getName%28%29, the Thread name은 char 배열로 변환 된 후'getName()'에 대한 String으로 다시 변환됩니다. –

관련 문제