日期:2014-05-20 浏览次数:20953 次
public class ThreadWaitNotify {
public static void main(String[] args) throws Exception {
Thread t = new Thread(){
public void run() {
try {
System.out.println("Thread sleep.....");
Thread.sleep(2 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("NotifyAll!");
synchronized (this) {
this.notifyAll();
}
}
};
t.start();
System.out.println("I am waiting.");
synchronized (t) {
t.wait();
}
System.out.println("Awaken.");
}
}
------解决方案--------------------
main也是个线程嘛,帮1楼的改下。
public class Test04
{
public static void main(String[] args)
{
Thread2 thread2 = new Thread2();
Thread1 thread1 = new Thread1(thread2);
thread2.start();
thread1.start();
}
}
class Thread1 extends Thread
{
private Thread2 thread2;
public Thread1(Thread2 thread2)
{
this.thread2 = thread2;
}
public void run()
{
try
{
synchronized (thread2)
{
System.out.println("thread2 wait.");
thread2.wait();
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("thread2 wakeup.");
}
}
class Thread2 extends Thread
{
public void run()
{
try
{
Thread.sleep(2000);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (this)
{
this.notifyAll();
}
}
}