建立執行緒的兩種方法 :
class thread1 extends thread
}class thread2 implements runnable
}class thread_main
}}
輸出結果:
thread-2 1
thread-1 1
mainthread 1
thread-3 1
mainthread 2
thread-1 2
thread-2 2
thread-1 3
mainthread 3
thread-3 2
mainthread 4
thread-1 4
thread-2 3
thread-1 5
mainthread 5
thread-3 3
mainthread 6
thread-1 6
thread-2 4
thread-1 7
mainthread 7
thread-3 4
mainthread 8
thread-1 8
thread-2 5
thread-1 9
mainthread 9
thread-3 5
thread-2 6
thread-3 6
thread-2 7
thread-3 7
thread-2 8
thread-3 8
thread-2 9
thread-3 9
錯誤案例:
建立多執行緒的兩種方法:
class thread1 extends thread
}class thread2 implements runnable
}class thread_main
}}
輸出結果:
mainthread 1
thread-1 1
thread-2.0 1
thread-0 1
thread-2.0 3
thread-1 2
mainthread 2
thread-1 5
thread-2.0 4
thread-0 2
thread-2.0 7
thread-1 6
mainthread 3
thread-1 9
thread-2.0 8
thread-0 3
mainthread 4
thread-0 4
mainthread 5
thread-0 5
mainthread 6
thread-0 6
mainthread 7
thread-0 7
mainthread 8
thread-0 8
mainthread 9
thread-0 9
*執行緒的執行結果是隨機的,關鍵看執行緒搶占cpu的具體情況 Java多執行緒學習之 建立執行緒
實現多執行緒的方法有3種 1 繼承thread類 thread實現了runnable介面 public class mythread extends thread 呼叫 mythread mt new mythread mt.start 2 實現runnable介面 public class myr...
Java建立多執行緒
到目前為止,我們僅用到兩個執行緒 主線程和乙個子執行緒。然而,你的程式可以建立所需的更多執行緒。例如,下面的程式建立了三個子執行緒 create multiple threads.class newthread implements runnable this is the entry point ...
Java建立多執行緒
繼承 thread 方式建立子執行緒 1.建立乙個繼承thread的子類 2.重寫thread類的run 方法,實現子執行緒要完成的功能 3.在主線程類中建立乙個子執行緒類的物件 4.呼叫子執行緒類的start 方法,啟動此子執行緒 實際上start 方法是呼叫了該類的run 方法 package ...