Java建立多執行緒

2021-08-05 18:30:11 字數 943 閱讀 4465

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

// create multiple threads.

class newthread implements runnable

// this is the entry point for thread.

public void run()

} catch (interruptedexception e)

system.out.println(name + " exiting.");}}

class multithreaddemo catch (interruptedexception e)

system.out.println("main thread exiting.");}}

程式輸出如下所示:

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建立多執行緒

繼承 thread 方式建立子執行緒 1.建立乙個繼承thread的子類 2.重寫thread類的run 方法,實現子執行緒要完成的功能 3.在主線程類中建立乙個子執行緒類的物件 4.呼叫子執行緒類的start 方法,啟動此子執行緒 實際上start 方法是呼叫了該類的run 方法 package ...

Java多執行緒 建立

一,繼承thread類建立執行緒類 定義thread子類,重寫該類的run 方法,run 方法代表了執行緒需要完成的任務 建立thread子類例項,即執行緒物件 呼叫執行緒物件的start 方法啟動該執行緒 public class firstthread extends thread public...

Java建立多執行緒

第一種方式 建立thread子類 實現步驟 1.建立乙個thread類的子類 2.在thread類的子類中重寫thread類中的run方法,設定執行緒任務 3.建立thread類的子類物件 4.呼叫thread類中的方法start方法,開啟新的執行緒,執行run方法 建立乙個thread類的子類so...