日期:2014-05-20 浏览次数:20856 次
public class ThreadTest { private Thread child = null; /** * @param args */ public static void main(String[] args) { ThreadTest test = new ThreadTest(); test.work(); } public void work() { myThread1 thread1 = new myThread1(); myThread2 thread2 = new myThread2(); //将第二个线程的引用赋值给成员变量child this.child = thread2; thread1.start(); thread2.start(); } class myThread1 extends Thread { public void run() { synchronized(child) { try { child.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("我睡醒了,现在开始打印信息"); } } } class myThread2 extends Thread { public void run() { synchronized(this) { try { sleep(5 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("唤醒另一个线程吧"); this.notifyAll(); } } } }
------解决方案--------------------
忘记加注释了
public class ThreadTest { private Thread child = null; /** * @param args */ public static void main(String[] args) { ThreadTest test = new ThreadTest(); test.work(); } public void work() { myThread1 thread1 = new myThread1(); myThread2 thread2 = new myThread2(); //将第二个线程的引用赋值给成员变量child this.child = thread2; thread1.start(); thread2.start(); } class myThread1 extends Thread { public void run() { synchronized(child) { try { //取得第二个Thread object reference,然后调用wait() child.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("我睡醒了,现在开始打印信息"); } } } class myThread2 extends Thread { public void run() { synchronized(this) { try { sleep(5 * 1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("唤醒另一个线程吧"); this.notifyAll(); } } } }