LockSupport Park Unpark Handoff
Coordinate two threads with LockSupport.park and unpark: a one-slot permit means unpark before park never blocks, unlike wait/notify ordering.
Code
import java.util.concurrent.locks.LockSupport;
public class PermitHandoff {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
System.out.println("worker: parking");
LockSupport.park(); // 无凭证则挂起
System.out.println("worker: unparked, running");
LockSupport.park(); // 凭证已消耗,再次 park 挂起
System.out.println("worker: never reaches here");
});
worker.start();
// 先 unpark 再 park 也安全:许可证至多一张,park 立即返回
LockSupport.unpark(worker);
Thread.sleep(50); // 让 worker 消耗掉这张许可
worker.join(200);
System.out.println("state = " + worker.getState()); // WAITING:第二次 park 挂起
LockSupport.unpark(worker); // 释放,演示结束
}
}How the snippet works
The code’s whole job belongs to the class PermitHandoff.
Applying it
Running the file prints labeled results such as worker: parking, worker: unparked, running, worker: never reaches here — each operation’s effect is visible in the output.
Statements that matter
Thread.sleep(50); // 让 worker 消耗掉这张许可
worker.join(200);
Thread worker = new Thread(() -> {
System.out.println("worker: parking");
LockSupport.park(); // 无凭证则挂起
System.out.println("worker: unparked, running");
LockSupport.park(); // 凭证已消耗,再次 park 挂起
System.out.println("worker: never reaches here");
});
Interactive Tools for This Topic
FAQ
- What does LockSupport Park Unpark Handoff print when run?
- Running the file directly is enough — expect labeled output lines such as `worker: parking`, `worker: unparked, running`, `worker: never reaches here`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.