jfml
发贴: 708
积分: 30
|
于 2003-06-03 16:15
程序如下: public class ThreadTester { public static boolean flag = false;
public static void main(String[] args) { ThreadTester tt = new ThreadTester();
MonitorThread dpt = new MonitorThread(); WorkThread wpt = new WorkThread();
dpt.start(); wpt.start();
tt.pauseSelf(); tt.goOn(); }
public ThreadTester() { }
public void goOn() { for (int i = 0; i < 10; i++) { System.out.println("OKay!"); } }
public synchronized void pauseSelf() { try { System.out.println( "Main Thread " + Thread.currentThread() + " waiting..."); wait(); System.out.println("Main Thread " + Thread.currentThread() + " go on..."); } catch (InterruptedException e) { e.printStackTrace(); } } }
class WorkThread extends Thread { public void run() { System.out.println( "Work Thread " + Thread.currentThread() + " changed flag's value to true!"); ThreadTester.flag = true; } }
class MonitorThread extends Thread { public void run() { while (!ThreadTester.flag) { System.out.println( "MonitorThread " + Thread.currentThread() + " watching the flag!"); }
synchronized (this) { System.out.println( "Monitor Thread " + Thread.currentThread() + " waking every waited thread!"); notifyAll(); } }
运行结果如下: Main Thread Thread[main,5,main] waiting... MonitorThread Thread[Thread-1,5,main] watching the flag! MonitorThread Thread[Thread-1,5,main] watching the flag! MonitorThread Thread[Thread-1,5,main] watching the flag! MonitorThread Thread[Thread-1,5,main] watching the flag! MonitorThread Thread[Thread-1,5,main] watching the flag! MonitorThread Thread[Thread-1,5,main] watching the flag! MonitorThread Thread[Thread-1,5,main] watching the flag! MonitorThread Thread[Thread-1,5,main] watching the flag! MonitorThread Thread[Thread-1,5,main] watching the flag! MonitorThread Thread[Thread-1,5,main] watching the flag! MonitorThread Thread[Thread-1,5,main] watching the flag! MonitorThread Thread[Thread-1,5,main] watching the flag! MonitorThread Thread[Thread-1,5,main] watching the flag! Work Thread Thread[Thread-2,5,main] changed flag's value to true! MonitorThread Thread[Thread-1,5,main] watching the flag! Monitor Thread Thread[Thread-1,5,main] waking every waited thread!
最后Main Thread并未被notify,请问原因何在呢,该如何修改
谢谢
|