Thread

2023/09/25閱讀時間約 4 分鐘

程式建立thread,然後會交給硬體中的scheduler去排定執行、切換資源

我們無法強制指定順序,因為電腦有太多任務需要執行,但資源有限,因此會由scheduler去分配、切換資源

電腦能同時執行多項任務,我現在在打字、播youtube聽音樂、跟朋友傳line訊息、下載圖片

雖然程式中可以設定thread的priority,但也只能起到"建議"scheduler的作用,告訴scheduler這一個thread的優先級比較高或比較低,因為還要處理很多跟你程式沒直接關係的任務,因此沒辦法保證一定會依照你設的priority順序執行


Race Condition

如何避免多執行緒同時對一個method或參數做操作? 加上synchronized

class Calculator{
int count;
public synchronized void increment(){
count++;
}
}

因此每次只能有一個thread能使用increment這個method,其他的thread都必須等待


完整程式範例

class Calculator{
int count;
public synchronized void increment(){
count++;
}
}

public class Demo {
public static void main(String[] args) {

Calculator calculator = new Calculator();

Thread t1 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
calculator.increment();
}
});

Thread t2 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
calculator.increment();
}
});

t1.start();
t2.start();

try {
t1.join();
t2.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}

System.out.println(calculator.count);

}
}

建立兩個thread,t1和t2,分別對Calculator的increment method執行10,000次(數字越大越明顯)

如果第3行沒有synchronized 的話,結果(第35行)就不會輸出預期的20,000

因為中途難免會出現兩個thread同時執行increment的情形

所以需要synchronized


29、30行,join method 的目的是要等thread的內容執行完

才能讓35行印出結果,不然會程式才不會等t1和t2執行完,馬上就會印出結果 0


Thread States 執行緒的狀態

raw-image
  • new: 創建thread
  • runnable: 交給scheduler,待它排定執行(說是排定但其實幾乎都是瞬間的事情)
  • running: 執行
  • waiting: 等待執行完所有該thread該做的事情。做完之後會通知scheduler說可以換別人了
  • dead: 被程式強制終止。常見於終止整個應用程式時


我的Java學習日記
留言0
查看全部
發表第一個留言支持創作者!