Java7併發程式設計實戰(一) 執行緒的管理

2021-09-08 11:10:15 字數 2590 閱讀 7658

1:繼承thread類,並且覆蓋run()方法

2:建立乙個實現runnable介面的類。使用帶引數的thread構造器來構造

2:example-->計算列印乘法表

首先建立乙個calculator類,實現runnable介面

public

class calculator implements

runnable

/*** method that do the calculations

*/@override

public

void

run() }}

view code

在main方法中呼叫

public

class

main }}

列印結果可以看到執行緒的無序性

thread-1: 2 * 1 = 2thread-8: 9 * 1 = 9thread-9: 10 * 1 = 10thread-9: 10 * 2 = 20thread-5: 6 * 1 = 6thread-2: 3 * 1 = 3thread-3: 4 * 1 = 4thread-3: 4 * 2 = 8thread-3: 4 * 3 = 12thread-3: 4 * 4 = 16thread-3: 4 * 5 = 20thread-3: 4 * 6 = 24thread-3: 4 * 7 = 28thread-3: 4 * 8 = 32thread-3: 4 * 9 = 36thread-3: 4 * 10 = 40thread-4: 5 * 1 = 5thread-7: 8 * 1 = 8thread-7: 8 * 2 = 16thread-7: 8 * 3 = 24thread-7: 8 * 4 = 32thread-7: 8 * 5 = 40thread-7: 8 * 6 = 48thread-6: 7 * 1 = 7thread-6: 7 * 2 = 14thread-6: 7 * 3 = 21thread-6: 7 * 4 = 28thread-6: 7 * 5 = 35thread-6: 7 * 6 = 42thread-6: 7 * 7 = 49thread-6: 7 * 8 = 56thread-6: 7 * 9 = 63thread-6: 7 * 10 = 70thread-0: 1 * 1 = 1thread-7: 8 * 7 = 56thread-4: 5 * 2 = 10thread-4: 5 * 3 = 15thread-4: 5 * 4 = 20thread-4: 5 * 5 = 25thread-4: 5 * 6 = 30thread-4: 5 * 7 = 35thread-4: 5 * 8 = 40thread-4: 5 * 9 = 45thread-2: 3 * 2 = 6thread-2: 3 * 3 = 9thread-5: 6 * 2 = 12thread-5: 6 * 3 = 18thread-5: 6 * 4 = 24thread-9: 10 * 3 = 30thread-9: 10 * 4 = 40thread-9: 10 * 5 = 50thread-9: 10 * 6 = 60thread-8: 9 * 2 = 18thread-1: 2 * 2 = 4thread-1: 2 * 3 = 6thread-1: 2 * 4 = 8thread-1: 2 * 5 = 10thread-1: 2 * 6 = 12thread-1: 2 * 7 = 14thread-1: 2 * 8 = 16thread-1: 2 * 9 = 18thread-1: 2 * 10 = 20thread-8: 9 * 3 = 27thread-8: 9 * 4 = 36thread-9: 10 * 7 = 70thread-5: 6 * 5 = 30thread-5: 6 * 6 = 36thread-5: 6 * 7 = 42thread-5: 6 * 8 = 48thread-5: 6 * 9 = 54thread-5: 6 * 10 = 60thread-2: 3 * 4 = 12thread-2: 3 * 5 = 15thread-2: 3 * 6 = 18thread-2: 3 * 7 = 21thread-2: 3 * 8 = 24thread-2: 3 * 9 = 27thread-2: 3 * 10 = 30thread-4: 5 * 10 = 50thread-7: 8 * 8 = 64thread-0: 1 * 2 = 2thread-0: 1 * 3 = 3thread-0: 1 * 4 = 4thread-7: 8 * 9 = 72thread-9: 10 * 8 = 80thread-9: 10 * 9 = 90thread-9: 10 * 10 = 100thread-8: 9 * 5 = 45thread-8: 9 * 6 = 54thread-8: 9 * 7 = 63thread-8: 9 * 8 = 72thread-8: 9 * 9 = 81thread-8: 9 * 10 = 90thread-7: 8 * 10 = 80thread-0: 1 * 5 = 5thread-0: 1 * 6 = 6thread-0: 1 * 7 = 7thread-0: 1 * 8 = 8thread-0: 1 * 9 = 9thread-0: 1 * 10 = 10

Java7併發程式設計實戰(一) 執行緒的等待

試想乙個情景,有兩個執行緒同時工作,還有主線程,乙個執行緒負責初始化網路,乙個執行緒負責初始化資源,然後需要兩個執行緒都執行完畢後,才能執行主線程 首先建立乙個初始化資源的執行緒 public class datasourcesloader implements runnable catch int...

Java7併發程式設計實戰(一) 執行緒的中斷

控制線程中斷的方法一般常規是定義乙個布林值,然後while 布林值 去執行,當想停止該執行緒時候,把布林值設為false.這裡我們來看第二種,interrupt interruptedexception 異常public class test implements runnable catch in...

JAVA7併發程式設計手冊筆記

isinterrupted 不能改變interrupted屬性值,只是返回這個屬性的值 thread類的靜態方法interrupted設定interrupted屬性為false。推薦使用isinterrupted deuqe 雙端佇列 uncaughtexceptionhandler介面 實現 un...