共計 1252 個字符,預(yù)計需要花費 4 分鐘才能閱讀完成。
可以使用 synchronized 關(guān)鍵字和 wait()、notify() 方法來實現(xiàn)兩個線程交替打印。
下面是一個簡單的例子,其中 A 線程打印奇數(shù),B 線程打印偶數(shù)。
public class AlternatePrint {private int count = 1;
private final Object lock = new Object();
public static void main(String[] args) {AlternatePrint alternatePrint = new AlternatePrint();
Thread threadA = new Thread(() -> alternatePrint.printOdd());
Thread threadB = new Thread(() -> alternatePrint.printEven());
threadA.start();
threadB.start();}
public void printOdd() {while (count <= 100) {synchronized (lock) {if (count % 2 != 0) {System.out.println(Thread.currentThread().getName() + ": " + count);
count++;
lock.notify(); // 喚醒等待的線程
} else {try {lock.wait(); // 當(dāng)前線程等待
} catch (InterruptedException e) {e.printStackTrace();
}
}
}
}
}
public void printEven() {while (count <= 100) {synchronized (lock) {if (count % 2 == 0) {System.out.println(Thread.currentThread().getName() + ": " + count);
count++;
lock.notify(); // 喚醒等待的線程
} else {try {lock.wait(); // 當(dāng)前線程等待
} catch (InterruptedException e) {e.printStackTrace();
}
}
}
}
}
}
在上面的例子中,使用一個共享的 lock 對象作為鎖,每個線程通過 synchronized(lock) 來獲取鎖對象。當(dāng) count 為奇數(shù)時,A 線程打印并增加 count,然后調(diào)用 lock.notify() 方法喚醒正在等待的 B 線程。當(dāng) count 為偶數(shù)時,B 線程打印并增加 count,然后調(diào)用 lock.notify() 方法喚醒正在等待的 A 線程。如果 count 的值不符合當(dāng)前線程的打印條件時,當(dāng)前線程調(diào)用 lock.wait() 方法進入等待狀態(tài),直到被喚醒。
需要注意的是,lock.wait() 和 lock.notify() 方法只能在 synchronized 塊中調(diào)用,否則會拋出 IllegalMonitorStateException 異常。同時,線程的啟動順序不確定,所以 A 和 B 線程的打印順序可能會有不同。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完