Re-entrant Locks
来源:互联网 发布:lgd和淘宝 编辑:程序博客网 时间:2024/06/05 14:30
1. 可以多次重入,只不过也要多次释放锁而已
2. unlock最好放在finally块里面,这样就可以保证即使获得锁后运行抛异常,也可以释放锁
3. lock里面Condition的await和signal对应synchronized的wait notify
4. signal运行后只有unlock了另外一个线程才能被唤醒
5. 使用Lock而不是synchronized的好处是可以使用try lock,这样就可以避免死锁,具体见下一篇博客
/* * Re-entrant Locks */public class App {public static void main(String[] args) throws InterruptedException {final Runner runner = new Runner();Thread t1 = new Thread(new Runnable(){public void run() {try {runner.firstThread();} catch (InterruptedException e) {e.printStackTrace();}}});Thread t2 = new Thread(new Runnable(){public void run() {try {runner.secondRunner();} catch (InterruptedException e) {e.printStackTrace();}}});t1.start();t2.start();t1.join();t2.join();runner.finished();}}
import java.util.Scanner;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/* *Re-entrant Locks */public class Runner {private int count = 0;private Lock lock = new ReentrantLock();private Condition cond = lock.newCondition();private void increment() {for(int i=0; i<1000; i++) {count ++;}}public void firstThread() throws InterruptedException {lock.lock();System.out.println("waiting ...");cond.await();System.out.println("wake up ... ");try {increment();} finally {lock.unlock();}}public void secondRunner() throws InterruptedException {Thread.sleep(1000);lock.lock();System.out.println("press the return key.");new Scanner(System.in).nextLine();System.out.println("get return key.");cond.signal();try {increment();} finally {lock.unlock();}}public void finished() {System.out.println("count is:" + count);}}
如果把secondRunner中的unlock注释掉那么就不会唤醒firstThread
0 0
- Re-entrant Locks
- Multi-Programming-10 Re-entrant Locks
- Understanding Re-entrant Kernels
- RE
- re
- re
- RE
- re
- re
- re
- re
- re
- re
- Re
- re
- re
- RE
- re
- 指针和引用的区别
- Egret typescript二维码生成库
- 安卓移动逆向(扫盲)
- 莫队——BZOJ3289 Mato的文件管理
- 经典读者写者问题
- Re-entrant Locks
- 快速排序的递归和非递归的实现
- [Android逆向]-Android逆向基础
- 浅谈CSS hack
- 1、设计模式之一
- 用plotrix包做双坐标轴图
- apt-get 命令总结
- Python元类编程——with_metaclass
- 异常