当前位置: 首页 > news >正文

【JUC】08-线程等待与唤醒

1. Object wait和notify实现等待与唤醒

没有锁会报错。

public class demo01 {public static void main(String[] args) {Object objectLock = new Object();new Thread(()->{synchronized (objectLock) {try {// 释放当前锁, 等待notify, 必须先使用wait才能使用notifyobjectLock.wait();} catch (InterruptedException e) {throw new RuntimeException(e);}System.out.println("Thread 1");}}).start();new Thread(()->{synchronized (objectLock) {System.out.println("Thread 2");objectLock.notify();}}).start();}
}

2. Lock.newCondition await和signal实现等待与唤醒

public class demo02 {public static void main(String[] args) {Lock lock = new ReentrantLock();Condition condition = lock.newCondition();new Thread(()->{lock.lock();try {// 释放锁并等待通知condition.await();System.out.println("Thread 1");} catch (InterruptedException e) {throw new RuntimeException(e);} finally {lock.unlock();}}).start();new Thread(()->{lock.lock();System.out.println("Thread 2");condition.signal();lock.unlock();}).start();}
}

3. LockSupport park和unpark实现等待与唤醒

unpark只能产生一个permit,且可以提前产生,

public class demo03 {public static void main(String[] args) {Thread thread = new Thread(() -> {try {TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {throw new RuntimeException(e);}// 可以先进行 unpark, 并且 permit 只能有一个// 需要两个permitLockSupport.park();LockSupport.park();System.out.println("Thread1");});thread.start();new Thread(()->{System.out.println("Thread 2");// 只会产生一个permitLockSupport.unpark(thread);LockSupport.unpark(thread);}).start();}
}

http://www.mrgr.cn/news/17530.html

相关文章:

  • 搭建IPsec VPN隧道解决PLC设备与主控上位机无法使用公网IP进行通信的问题
  • [STM32]从零开始的STM32标准库环境搭建(小白向)
  • 【读书笔记-《30天自制操作系统》-13】Day14
  • Ai Illustrator 取消吸附到像素点,鼠标拖动的时候只能到像素点
  • pg 唯一性约束修复
  • ConcurrentHashmap面试【高频】
  • 家里装修如何选择五金件?听商家说还是信品牌
  • 经典大语言模型解读(2):生成式预训练的先锋GPT-1
  • MySQL基础操作
  • 第8讲 ,ISP 串口程序下载
  • 快速构建一个ui界面程序--pyqt入门
  • springboot 整合mongoDB
  • 简述线性表、栈和队列的异同
  • stm32开发之rt-thread使SysTick处于微妙级运行时,出现的问题记录
  • shell了解和问答机制
  • 学习周报-2024.8.31
  • 全国大学生数学建模竞赛系统使用手册
  • C语言程序设计
  • C语言典型例题58
  • ModuleNotFoundError: No module named ‘cv2‘,python