標籤:
到目前為止,我們僅用到兩個線程:主線程和一個子線程。然而,你的程式可以建立所需的更多線程。例如,下面的程式建立了三個子線程:
1 // Create multiple threads. 2 class NewThread implements Runnable { 3 String name; // name of thread 4 Thread t; 5 NewThread(String threadname) { 6 name = threadname; 7 t = new Thread(this, name); 8 System.out.println("New thread: " + t); 9 t.start(); // Start the thread10 }11 12 // This is the entry point for thread.13 public void run() {14 try {15 for(int i = 5; i > 0; i--) {16 System.out.println(name + ": " + i);17 Thread.sleep(1000);18 }19 } catch (InterruptedException e) {20 System.out.println(name + "Interrupted");21 }22 System.out.println(name + " exiting.");23 }24 }25 26 class MultiThreadDemo {27 public static void main(String args[]) {28 new NewThread("One"); // start threads29 new NewThread("Two");30 new NewThread("Three");31 try {32 // wait for other threads to end33 Thread.sleep(10000);34 } catch (InterruptedException e) {35 System.out.println("Main thread Interrupted");36 }37 System.out.println("Main thread exiting.");38 }39 }
程式輸出如下所示:
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Three: 2
Two: 2
One: 1
Three: 1
Two: 1
One exiting.
Two exiting.
Three exiting.
Main thread exiting.
如你所見,一旦啟動,所有三個子線程共用CPU。注意main()中對sleep(10000)的調用。這使主線程沉睡十秒確保它最後結束。
系列文章:
Java知多少(上)
Java知多少(39)interface介面
Java知多少(40)介面和抽象類別的區別
Java知多少(41)泛型詳解
Java知多少(42)泛型萬用字元和型別參數的範圍
Java知多少(43)異常處理基礎
Java知多少(44)異常類型
Java知多少(45)未被捕獲的異常
Java知多少(46)try和catch的使用
Java知多少(47)多重catch語句的使用
Java知多少(48)try語句的嵌套
Java知多少(49)throw:異常的拋出
Java知多少(50)Java throws子句
Java知多少(51)finally
Java知多少(52)內建異常
Java知多少(53)使用Java建立自己的異常子類
Java知多少(54)斷言詳解
Java知多少(55)線程
Java知多少(56)執行緒模式Java知多少(57)主線程Java知多少(58)線程Runnable介面和Thread類詳解
Java知多少(59)建立多線程