Java知多少(59)建立多線程

來源:互聯網
上載者:User

標籤:

到目前為止,我們僅用到兩個線程:主線程和一個子線程。然而,你的程式可以建立所需的更多線程。例如,下面的程式建立了三個子線程:

 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)建立多線程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.