synchronized實現,悲觀鎖的體現
public class Test2 {
public static void main(String[] args) throws InterruptedException {
//鎖對象,是線程競爭的資源
NumResource res = new NumResource(0);
//創建三個線程,參數:根據資源res的變化,判斷count條件是否滿足,來輸出結果ch
TestThread t1 = new TestThread(0, res, "A");
TestThread t2 = new TestThread(1, res, "B");
TestThread t3 = new TestThread(2, res, "C");
//啓動三個線程,無關順序
t2.start();
t3.start();
t1.start();
}
}
//線程類
class TestThread extends Thread {
//參數:根據鎖資源res的變化,判斷count條件是否滿足,來輸出結果ch
private int count;
private NumResource res;
private String ch;
public TestThread(int count, NumResource res, String ch) {
this.count = count;
this.res = res;
this.ch = ch;
}
@Override
public void run() {
// 每個線程循環搶奪資源鎖
while (res.num < 10) {
synchronized (res) {
//System.out.println(res.num);
//搶到鎖就判斷,是否滿足條件輸出結果
if (res.num % 3 == count) {
System.out.println(ch + " " + Thread.currentThread().getName());
//對鎖資源內容作更改
res.num++;
//激活一個線程,被激活的線程會從res.wait()語句下-行開始執行,並再一次嘗試搶奪資源鎖,沒有搶到就被卡到synchronized (res)處
res.notifyAll();
}
try {
// 暫停當前搶到res資源鎖的線程
res.wait();
//每個線程的結束條件,每個線程被喚醒後,會判斷是否滿足條件來進行推出
//若滿足,則表示當前線程要終止,並再一次調用res.notifyAll()來激活一個線程,因爲其他的線程都被卡到了res.wait(); 處,他們沒法得到執行並判斷自己是否要結束
if (res.num >= 10) {
res.notifyAll();
//跳出while循環,放棄搶奪資源的權力
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
//鎖資源
class NumResource {
//num的更改會判斷當前線程是否有結果輸出
int num;
public NumResource(int num) {
this.num = num;
}
}