Java Programming

wait/notify

tomato13 2009. 2. 28. 15:42

public class ThreadTest extends Thread {


public ThreadTest(String a_Str) {

super(a_Str);

}


public synchronized void run() {

try {

int l_Time = 10000;


System.out.println(getName() + ": waiting time: " + l_Time);

wait(l_Time);

System.out.println(getName() + ": waiting completes.");

} catch (Exception e) {

e.printStackTrace();

}

}


public synchronized void _notify() {

notify();

System.out.println("notified");

}


public static void main(String[] args) {

ThreadTest l_thread = new ThreadTest("Thread1");            // (0)


l_thread.start();

try {

Thread.sleep(1000);

} catch(Exception e) {

e.printStackTrace();

}

//l_thread._notify();                                                 // (1)


(new ThreadTest("Thread2") {

public synchronized void run() {

try {

int l_Time = 2000;


System.out.println(getName() + ": waiting timd: " + l_Time);

// Thread.sleep(2000);

notify();                                         // (2)

System.out.println(getName() + " notified");

} catch (Exception e) {

e.printStackTrace();

}

}

}).start();

}

}


(1)의 경우에는 (0)의 "Thread1"의 wait에게 notify가 되지만 (2)의 경우에는 그러하지 못하다. 다른 객체이기 때문인 듯 하다. 어렵도다... ㅡ.ㅡ;;

p.s) 일반적인 socket programming에 있어서 client가 server에게 여러 msg를 보내고 각각의 msg.에 대해서 wait를 건다. 즉, response msg.를 기다리게 되는 것이다. 그리고 server는 notify를 하게 되면 client는 어떤 msg.에게 notify를 건네야할지 고민하게 된다. 때문에 아래와 같이 각각의 msg.에 대해서 request hash table을 구성하여 관리하게 된다.

   synchronized (_requests)
   {
Message message1 = (Message) _requests.get(obj);
if (message1 != null)
{
   message1.replyReceived(message);
}