2016-07-17 3 views
1

자바에서 나를 위해 대기 알림 메서드를 단순화 할 사람이 필요합니다. 저는 현재 200 개 사이트를 살펴 보았지만 여전히 이해할 수는 없습니다.자바 대기 동기화 된 키 워드를 사용하여 메서드를

내가 다른 스레드에서 호출 통지 될 때까지 하나 개의 스레드가 대기해야 할 필요가있는 프로그램을하고 있어요

...

class mainClass{ 
public static void main(String args[])throws Exception{ 
     Thread t1 = new Thread(new Runnable(){ 
      public void run(){ 
      //code inside to make thread t1 wait untill some other thread 
      //calls notify on thread t1? 
      } 
     }); 
     t1.start(); 


     synchronized(t1){ 
      //main thread calling wait on thread t1? 
      t1.wait(); 
     } 



     new Thread(new Runnable(){ 
      public void run(){ 
       try{ 
        synchronized(t1){ 
          t1.notify() //????? 
        } 
       }catch(Exception e1){} 
      } 
     }).start(); 
} 
} 
+1

[Object.wait] (https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#wait--), [스레드. 가입] (https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#join-long-). – VGR

+0

친구 감사합니다. – EchoCode

답변

1

대기가 1의 Runnable에서 일어날 필요가 있고 당신이 필요합니다 대기 할 Object 인스턴스에 대한 액세스이므로 t1 Thread 인스턴스가 작동하지 않습니다. 이 코드에서는 별도의 잠금 객체를 만들었습니다.

public static void main(String[] args) { 
    final Object lock = new Object(); 
    new Thread(new Runnable() { 
     @Override 
     public void run() { 
      synchronized(lock) { 
       try { 
        lock.wait(); 
        System.out.println("lock released"); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    }).start(); 
    System.out.println("before sleep"); 
    try { 
     Thread.sleep(1000); 
     System.out.println("before notify"); 
     synchronized(lock) { 
      lock.notify(); 
     } 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } 
} 

스레드 알림을 사용하면 테스트하기가 매우 어려울 수 있습니다. Akka과 같은 메시지 기반 접근 방식을 사용하는 것이 좋습니다.