Java线程控制
当 suspend(), resume()和stop()通过Thread类中定义的方法似乎是完全合理和方便的方式来管理线程的执行,他们不能被用于新的Java程序和过时的较新版本的java中。
下面的例子说明了wait()和notify()方法是从Object继承方法可以用来控制一个线程的执行。
这个例子是类似于前面一节中的程序。然而,废弃的方法调用已被删除。让我们看看这个程序的运行。
NewThread类包含一个名为suspendFlag一个Boolean实例变量,它用来控制线程的执行。它是通过构造函数初始化为false。
在run()方法包含检查suspendFlag同步语句块。如果该变量为true,则wait()方法被调用来暂停线程的执行。mysuspend()方法设置suspendFlag为true。myresume()方法设置suspendFlag为false,然后调用notify()方法来唤醒线程。最后,main()方法已被修改以调用mysuspend()和myresume()方法。
例子:
// Suspending and resuming a thread for Java 2 class NewThread implements Runnable { String name; // name of thread Thread t; boolean suspendFlag; NewThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); suspendFlag = false; t.start(); // Start the thread } // This is the entry point for thread. public void run() { try { for(int i = 15; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(200); synchronized(this) { while(suspendFlag) { wait(); } } } } catch (InterruptedException e) { System.out.println(name + " interrupted."); } System.out.println(name + " exiting."); } void mysuspend() { suspendFlag = true; } synchronized void myresume() { suspendFlag = false; notify(); } } public class SuspendResume { public static void main(String args[]) { NewThread ob1 = new NewThread("One"); NewThread ob2 = new NewThread("Two"); try { Thread.sleep(1000); ob1.mysuspend(); System.out.println("Suspending thread One"); Thread.sleep(1000); ob1.myresume(); System.out.println("Resuming thread One"); ob2.mysuspend(); System.out.println("Suspending thread Two"); Thread.sleep(1000); ob2.myresume(); System.out.println("Resuming thread Two"); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } // wait for threads to finish try { System.out.println("Waiting for threads to finish."); ob1.t.join(); ob2.t.join(); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Main thread exiting."); } }
此处是由上述程序所产生的输出:
New thread: Thread[One,5,main] One: 15 New thread: Thread[Two,5,main] Two: 15 One: 14 Two: 14 One: 13 Two: 13 One: 12 Two: 12 One: 11 Two: 11 Suspending thread One Two: 10 Two: 9 Two: 8 Two: 7 Two: 6 Resuming thread One Suspending thread Two One: 10 One: 9 One: 8 One: 7 One: 6 Resuming thread Two Waiting for threads to finish. Two: 5 One: 5 Two: 4 One: 4 Two: 3 One: 3 Two: 2 One: 2 Two: 1 One: 1 Two exiting. One exiting. Main thread exiting.