Thread에서 wait 와 notify 은 어떠한 상황에서 쓰는지 예제를 통해 알아 보도록 합시다.
Wait() : 다른 Thread 에게 제어권을 넘겨주고 대기상태로 진입
notify() : wait() 되었던 것이 다시 실행상태가 됨
※ 각각은 Thread가 아닌 object에 정의되어 있어 각 쓰레드에서 호출 가능
※ 동기화 블록 내에서만 사용가능 (synchronized)
아래 조금 극단적인 예제를 들어보았다.
<Example-1>
public class Example1 { public static void main(String[] args){ sumThread th = new sumThread(); th.start();
System.out.println("Total is: " + th .total);
} } class sumThread extends Thread{ int total; @Override public void run(){ for(int i=0; i<100000 ; i++){ total += i; } //System.out.println("Final Total " + total); // 0~100000까지 합계값을 확인 } }
<결과>
Total is: 946000
Final Total 704982704
<문제점>
th.start();
System.out.println("Total is: " + th .total);
main 함수 안에서 print 하는 total 값이 맞지 않는다. 왜냐하면 아직도 sum 연산을 수행하고 있기 때문!
만약 wait와 notify 를 이용해서 해결하고싶다면. 아래와 같이 코드를 작성한다
public class Example3 { public static void main(String[] args){ SumThread th = new SumThread(); th.start(); synchronized(th){ try{ System.out.println("Wait......"); th.wait(); // notify에 의해서 wait가 해제됨 }catch(InterruptedException e){ e.printStackTrace(); } System.out.println("Total is: " + th.total); } } } class SumThread extends Thread{ int total; @Override public void run(){ synchronized(this){ for(int i=0; i<100000 ; i++){ total += i; } notify(); // 연산을 모두 마친후 notify } } }
<결과>
Wait......
Total is: 704982704
위 예제는 구글링해서 가져온걸 수정한겁니다.
저렇게 사용하지 않고 main에서 출력하려면
th.start() 다음에 th.join() 을 하면 그냥 해결 되는 문제입니다.
'Computer Science > JAVA' 카테고리의 다른 글
Thread-1 (Basic) (0) | 2015.12.03 |
---|---|
Hashmap 과 Treemap 의 차이 (0) | 2015.12.02 |
E-Clipse Java Font 수정 (0) | 2015.11.18 |
StringBuilder (0) | 2015.11.18 |
Inner Class(내부 클래스) (0) | 2015.11.18 |