Java Programming

wait, notify example

tomato13 2009. 2. 3. 14:58
public class ThreadTest extends Thread {
public ThreadTest(String a_Str) {
super(a_Str);
}
public synchronized void run() {
try {
int l_Time = 3000;

System.out.println(getName() + ": waiting time: " + l_Time);
wait(l_Time);
System.out.println(getName() + ": waiting completes.");
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
(new ThreadTest("Thread1")).start();

(new ThreadTest("Thread2") {
public synchronized void run() {
try {
int l_Time = 2000;
System.out.println(getName() + ": waiting timd: " + l_Time);
Thread.sleep(2000);
notify();
System.out.println(getName() + " notified");
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}

wait block에 sync가 걸리지 않으며 exception error를 발생한다. wait는 특정 thread를 잡고 있는 상태에서 사용되기 때문일듯(?)하다.