LockSupport简介
所属分类 java
浏览量 996
Lock ReentrantLock
AQS
线程间等待/通知机制 Condition
LockSupport.park() LockSupport.unpark()
阻塞和唤醒线程
LockSupport方法介绍
阻塞线程
void park() 阻塞当前线程
void park(Object blocker) blocker 用来记录导致线程阻塞的阻塞对象,方便问题排查 ,
void parkNanos(long nanos) 阻塞当前线程 增加超时
void parkNanos(Object blocker, long nanos)
void parkUntil(long deadline)
void parkUntil(Object blocker, long deadline)
唤醒线程
void unpark(Thread thread) 唤醒处于阻塞状态的指定线程
synchronzed 阻塞线程,进入 BLOCKED 状态
调用LockSupprt方法阻塞线程,进入 WAITING 状态
LockSupport park unpark 例子
import java.time.LocalDateTime;
import java.util.concurrent.locks.LockSupport;
public class LockSupportTest {
private static final String lockId = "lock001";
public static void main(String[] args) throws Exception {
Thread thread = new Thread(LockSupportTest::runPark);
thread.setName("parkthread");
thread.start();
Thread.sleep(30000);
LockSupport.unpark(thread);
}
private static void runPark() {
LockSupport.park(lockId);
// LockSupport.park();
System.out.println(Thread.currentThread().getName() + " uppark "+LocalDateTime.now());
}
}
park(Object blocker) 与 park() 线程堆栈区别
使用 park(Object blocker)
"parkthread" #9 prio=5 os_prio=31 tid=0x00007f8edf870000 nid=0x4603 waiting on condition [0x000070000b8ee000]
java.lang.Thread.State: WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
- parking to wait for <0x00000007955f19e8> (a java.lang.String)
at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
at LockSupportTest.runPark(LockSupportTest.java:16)
at LockSupportTest$$Lambda$1/531885035.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
parking to wait for <0x00000007955f19e8> (a java.lang.String)
使用 park()
"parkthread" #9 prio=5 os_prio=31 tid=0x00007fdbda855800 nid=0x4503 waiting on condition [0x00007000023ea000]
java.lang.Thread.State: WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
at java.util.concurrent.locks.LockSupport.park(LockSupport.java:304)
at LockSupportTest.runPark(LockSupportTest.java:18)
at LockSupportTest$$Lambda$1/531885035.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
AQS要点整理
AQS同步队列与条件队列
The java.util.concurrent Synchronizer Framework 翻译
上一篇
下一篇
进程io监控命令iopp
Stack ArrayDeque LinkedList
java线程状态及转换
ReentrantLock原理
基于 wait 和 notifyAll 实现简单的阻塞队列
基于 ReentrantLock Condition await signalAll 实现简单的阻塞队列