在学习 SynchronousQueue 时,看到了 LockSupport 这个工具类;
因此写了一个demo 去理解下 unpark 与 park 的所谓的 permit
package threads.park;
import java.util.concurrent.locks.LockSupport;
/**
* 用于理解 park 与 UnPark
* upPark 相当于免停命令,持有一次 unPark 免于下一次 park() 的叫停,但再一次 park(),将会block
*/
public class ParkTest {
public static void main(String[] args) throws InterruptedException {
unParkOneButPark2();
// unParkFirstParkThen();
}
static void unParkFirstParkThen() throws InterruptedException {
Thread t = new Thread(() ->
{
LockSupport.unpark(Thread.currentThread());
System.out.println("park itself first follow unPark");
LockSupport.park();
System.out.println("park itself second follow unPark");
LockSupport.park();
System.out.println("waked up by main thread");
}
);
t.setName("thread -0 ");
t.start();
// main give up cpu ,let t1 run first
t.join(5);
// after t block itself ,main run
LockSupport.unpark(t);
System.out.println("main has tried to unPark " + t.getName());
//park itself first follow unPark
//park itself second follow unPark
//waked up by main thread
//main has tried to unPark thread -0
}
static void unParkOneButPark2() throws InterruptedException {
Thread t = new Thread(() ->
{
System.out.println(Thread.currentThread().getName() + " will be blocked myself");
LockSupport.park();
System.out.println(Thread.currentThread().getName() + " end first block");
System.out.println(Thread.currentThread().getName() + " will call park again");
LockSupport.park();
}
);
t.setName("thread -1 ");
t.start();
// main give up cpu ,let t1 run
t.join(5);
LockSupport.unpark(t);
System.out.println("main thread unPark " + t.getName());
//thread -1 will be blocked
//main thread unPark thread -1
//thread -1 end first block
//thread -1 will call park again
}
}