How to control the behavior of wait() and notify()
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   vince_zhao
Posted On:   Wednesday, August 1, 2001 02:30 PM

The following code won't work, the waiting thread won't be awaken. I think the problem is it's waiting for a monitor associated with it's own object, thus the notify() call won't wake it up. How can I implement the similar senario? public class TestThread { public static void main( String [] s ) { new Thread1().start(); new Thread2().start(); } } class Thread1 extends Thread { private String name; public Thread1() { name = "Thread 1"; } public void run() { while( true ) runThread1();    More>>

The following code won't work, the waiting thread won't be awaken. I think the problem is it's waiting for a monitor associated with it's own object, thus the notify() call won't wake it up. How can I implement the similar senario?


public class TestThread

{

public static void main( String [] s )

{

new Thread1().start();

new Thread2().start();

}

}



class Thread1 extends Thread

{

private String name;

public Thread1()

{

name = "Thread 1";

}



public void run()

{

while( true )

runThread1();

}



private void runThread1()

{

System.out.println("Thread 1 started...");

try {

wait();

} catch ( InterruptedException e ) {}

System.out.println("Thread 1 waken up");

}

}



class Thread2 extends Thread

{

private String name;

public Thread2()

{

name = "Thread 2";

}

public void run()

{

runThread2();

}



private void runThread2()

{

while( true )

{

System.out.println("Thread 2 started...");

//try to wake up thread1

getInput();

if( certain input )

notify();

System.out.println("Notified...");

}

}

}

.

   <<Less

Re: How to control the behavior of wait() and notify()

Posted By:   Edward_Harned  
Posted On:   Thursday, August 2, 2001 01:51 PM

In order for threads to talk to each other, they must both lock on the same Monitor.



Your wait() and notify() cannot work because you have not locked the monitor for the thread object.



The full explanation is far too lengthy to repeat here. There are numerous examples of wait/notify in every book on Java. You may also see Allen Holub's articles on threading at
http://www.javaworld.com/ and his latest



Warning! Threading in a multiprocessor world, by Allen Holub

http://www.javaworld.com/jw-02-2001/jw-0209-toolbox.html

Re: How to control the behavior of wait() and notify()

Posted By:   Cory_Powers  
Posted On:   Thursday, August 2, 2001 05:19 AM

Try using notifyAll() instead of notify().
About | Sitemap | Contact