yield() 的作用是「讓步」:讓當前線程從「運行狀態」進入「就緒狀態」,從而讓給其他相同優先級的等待線程獲取執行權。但 不保證 其他線程一定能獲得執行權,當前線程也可能再次進入運行狀態繼續執行。
// YieldTest.java
class ThreadA extends Thread {
public ThreadA(String name) { super(name); }
public synchronized void run() {
for (int i = 0; i < 10; i++) {
System.out.printf("%s [%d]:%d\n", this.getName(), this.getPriority(), i);
if (i % 4 == 0) Thread.yield(); // 每 4 次讓步
}
}
}
public class YieldTest {
public static void main(String[] args) {
ThreadA t1 = new ThreadA("t1");
ThreadA t2 = new ThreadA("t2");
t1.start();
t2.start();
}
}
t1 [5]:0 t2 [5]:0 t1 [5]:1 t1 [5]:2 t1 [5]:3 t1 [5]:4 t1 [5]:5 t1 [5]:6 t1 [5]:7 t1 [5]:8 t1 [5]:9 t2 [5]:1 t2 [5]:2 t2 [5]:3 t2 [5]:4 t2 [5]:5 t2 [5]:6 t2 [5]:7 t2 [5]:8 t2 [5]:9
t1 在能被 4 整除時調用 yield(),但並未切換到 t2。這證明 yield() 僅將線程置為就緒狀態,不強制上下文切換,即使同優先級線程存在也不一定獲得 CPU。
| 特性 | wait() | yield() |
|---|---|---|
| 狀態轉換 | 運行 → 等待(阻塞) | 運行 → 就緒 |
| 鎖釋放 | 釋放同步鎖 | 不釋放鎖 |
// YieldLockTest.java
public class YieldLockTest {
private static Object obj = new Object();
public static void main(String[] args) {
ThreadA t1 = new ThreadA("t1");
ThreadA t2 = new ThreadA("t2");
t1.start(); t2.start();
}
static class ThreadA extends Thread {
public ThreadA(String name) { super(name); }
public void run() {
synchronized (obj) { // 共享鎖
for (int i = 0; i < 10; i++) {
System.out.printf("%s [%d]:%d\n", this.getName(), this.getPriority(), i);
if (i % 4 == 0) Thread.yield();
}
}
}
}
}
t1 [5]:0 t1 [5]:1 ... t1 [5]:9 t2 [5]:0 ... t2 [5]:9
t1 調用 yield() 時未釋放 obj 鎖,導致 t2 一直阻塞,直到 t1 運行完畢釋放鎖。