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.