ReentrantLock中的Condition(等待和唤醒)
2024-09-05 05:13:00
Condition 类的 awiat 方法和 Object 类的 wait 方法等效
Condition 类的 signal 方法和 Object 类的 notify 方法等效
Condition 类的 signalAll 方法和 Object 类的 notifyAll 方法等效
ReentrantLock 类可以唤醒指定条件的线程,而 object 的唤醒是随机的
synchronized方式对比下
public static Student student = null;
public static void waitTest() throws InterruptedException {
student = new Student();
Thread t1 = new Thread(() -> {
synchronized (student) {
System.out.println("t1 wait!");
try {
student.wait();
System.out.println("t1 开始重新run!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
Thread.sleep(3000);
Thread t2 = new Thread(() -> {
synchronized (student) {
System.out.println("t2 我通知了 notify!");
student.notify();
}
});
t2.start();
}
Condition实现方式
public static ReentrantLock lock = new ReentrantLock();
public static Condition condition = lock.newCondition();
private static void reentrantLock() throws InterruptedException {
Thread t1 = new Thread(() -> {
lock.lock();
try {
System.out.println("我进入了T1!");
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
System.out.println("释放T1锁!");
}
});
t1.start();
Thread.sleep(2000);
Thread t2 = new Thread(() -> {
lock.lock();
try {
System.out.println("我进入了T2!");
condition.signal();
System.out.println("我是T2,我唤醒了T1,T1进入等待状态!");
//condition.signalAll();
} finally {
lock.unlock();
System.out.println("释放T2锁!");
}
});
t2.start();
}
最新文章
- dubbox
- iOS阶段学习第19天笔记(协议-Protocol)
- C++ 代码换行
- starling 笔记
- nodejs学习[持续更新]
- 学习web前端技术的笔记,仅供自己查阅备忘,移动对font-size的控制(并非原创)
- 11 PopupMenu菜单和代码例子
- C++ 命名管道 与Winform跨进程通信
- [Codeforces896C] Willem, Chtholly and Seniorious (ODT-珂朵莉树)
- js扩展运算符(spread)三个点(...)
- ReportViewe调用Reporting Services报表时报错Session超时
- 30.Mysql常见问题和应用技巧
- winform(记事本--保存和退出)
- 【C#】C# in deep 笔记
- Use Jupyter notebook on Fedora 28
- 山寨一个std::bind\boost::bind
- POJ 3122 Pie
- linux安装spark-2.3.0集群
- 网络编程(Socket)
- 浏览器报错:unexpected end of input 解决方法