Java 开发 - LockSupport(提供了线程阻塞和唤醒的基础功能)
·
LockSupport
1、基本介绍
-
LockSupport 是 Java 并发包中的一个工具类,提供了线程阻塞和唤醒的基础功能,它是构建高级同步工具的基石(例如,AQS)
-
LockSupport 的底层是使用 Unsafe 类来实现的
2、基本使用
- 基本使用
Thread t1 = new Thread(() -> {
System.out.println(Thread.currentThread().getName() + ":进入");
LockSupport.park();
System.out.println(Thread.currentThread().getName() + ":被唤醒");
}, "t1");
t1.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + ":唤醒 " + t1.getName());
LockSupport.unpark(t1);
}, "t2").start();
# 输出结果
t1:进入
t2:唤醒 t1
t1:被唤醒
- 先唤醒后阻塞(许可证的预先授予)
Thread t1 = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":进入");
LockSupport.park();
System.out.println(Thread.currentThread().getName() + ":被唤醒");
}, "t1");
t1.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + ":唤醒 " + t1.getName());
LockSupport.unpark(t1);
}, "t2").start();
# 输出结果
t2:唤醒 t1
t1:进入
t1:被唤醒
- 超时阻塞
Thread t1 = new Thread(() -> {
System.out.println(Thread.currentThread().getName() + ":进入");
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(5));
System.out.println(Thread.currentThread().getName() + ":被唤醒");
}, "t1");
t1.start();
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + ":唤醒 " + t1.getName());
LockSupport.unpark(t1);
}, "t2").start();
# 输出结果
t1:进入
t1:被唤醒
t2:唤醒 t1
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
Thread t1 = new Thread(() -> {
System.out.println(Thread.currentThread().getName() + ":进入" + " [" + formatter.format(LocalDateTime.now()) + "]");
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(5));
System.out.println(Thread.currentThread().getName() + ":被唤醒" + " [" + formatter.format(LocalDateTime.now()) + "]");
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(10));
System.out.println(Thread.currentThread().getName() + ":再次被唤醒" + " [" + formatter.format(LocalDateTime.now()) + "]");
}, "t1");
t1.start();
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + ":唤醒 " + t1.getName() + " [" + formatter.format(LocalDateTime.now()) + "]");
LockSupport.unpark(t1);
}, "t2").start();
# 输出结果
t1:进入 [15:24:14]
t1:被唤醒 [15:24:19]
t2:唤醒 t1 [15:24:24]
t1:再次被唤醒 [15:24:24]
更多推荐




所有评论(0)