[英]Java-8 Thread in Loop
我創建這段代碼:
static int i;
public static void main(String[] args) throws InterruptedException {
for (i = 1; i <= 5; i++) {
new Thread(() -> {
hello(i);
}).start();
}
}
public static void hello(int i) {
System.out.println("Thread number = " + i);
}
當您查看此內容時,您會認為它會打印:
Thread number = 1
Thread number = 2
Thread number = 3
Thread number = 4
Thread number = 5
但這是不正確的,它會打印一個隨機int,並且它不打印邏輯6
有時像這樣:
Thread number = 5
Thread number = 6
Thread number = 6
Thread number = 6
Thread number = 6
我添加Thread.sleep(2000);
之后:
for (i = 1; i <= 5; i++) {
new Thread(() -> {
hello(i);
}).start();
Thread.sleep(2000);
}
它顯示了一個正確的結果:
Thread number = 1
Thread number = 2
Thread number = 3
Thread number = 4
Thread number = 5
為什么在第一個結果中顯示該結果,在第一個結果中顯示6,而實際上卻不存在6? 為什么不打印有序的1,2,3,...? 有什么解釋嗎?
當Thread
執行Runnable's
run
方法時,循環可能已經完成其執行,並且i
最后一次取值為6
,請記住您正在執行i<=5
,這意味着循環完成時i
將等於6
。
您得到的完全是邏輯輸出,您可能會得到更多的奇數打印輸出。 正如Thread中 start方法的javadoc所說:
結果是兩個線程同時運行:當前線程(從調用返回到start方法)和另一個線程(執行其run方法)。
sub Thread
在循環中開始執行的時間是不確定的,您得到的結果表明,在循環線程完成其最后一個循環之前執行了1個線程 ,在整個循環完成之后執行了4個其他線程。
添加Thread.sleep(2000);
后獲得預期訂單的原因Thread.sleep(2000);
之所以如此,是因為您給了每個sub Thread
足夠的時間來執行實際操作,僅此而已。 執行順序在本質上/理論上是不確定的。
如果像其他語言一樣,您的線程代碼是以不確定性的方式進行調度的,那么在運行線程代碼時,將訪問采用ACTUAL值的變量。
我重寫了一些更簡潔的代碼:
公共班級主要{
static int i = 0;
public static void main(String[] args) throws Exception
{
// Lambda Runnable
Runnable task = () -> {
hello(i);
};
for (i = 1; i <= 5; i++) {
new Thread(task).start();
}
}
public static void hello(int i) {
System.out.println("Thread number = " + i);
}
}
注意我必須將“ i”設置為靜態。
一個更清潔的解決方案是使用帶有“ i”的線程派生類並將其設置在構造函數中,因此子類的每個線程實例將具有自己的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.