本文主要是介绍Multi-Programming-10 Re-entrant Locks,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.What is the difference between synchronized and re-entrant lock?
这里是关于该问题的讨论。
中文简单解释一下:
问题:'synchronized'和 're-entrant lock'有什么不同,或者换种说法--这两种方式分别在哪些情形下适用?
解答:官方关于're-entrant lock'的解释--重入锁和内在对象监视器方式同步方法或代码块方式具有相同的行为和语法规则;但're-entrant lock'具有更多的扩展能力(翻译的不忍直视,请看原链接)。
2.Conditon await()/signal VS wait()/notify()?
可以查看stackoverflow上关于该问题的解释。
从代码上可以看出,同一个monitor可以有多个condition变量,也就是说:re-entrant lock支持多个wait()/notify()队列。
3.Code demo.
package com.fqy.mix;import java.util.Scanner;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;public class ReentrantLockDemo {public static void main(String[] args) {ReentrantLockDemoUtil.demonstrate();}}class ReentrantLockDemoUtil {public static void demonstrate() {SharedObjectRe sharedObjectRe = new SharedObjectRe();Thread t1 = new Thread(new Runnable() {@Overridepublic void run() {try {sharedObjectRe.stageOne();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});Thread t2 = new Thread(new Runnable() {@Overridepublic void run() {sharedObjectRe.stageTwo();}});t1.start();t2.start();try {t1.join();t1.join();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}sharedObjectRe.afterRunning();}
}class SharedObjectRe {private int count = 0;private ReentrantLock lock = new ReentrantLock();private Condition condition = lock.newCondition();private void increment() {for (int i = 0; i < 10000; i++) {count++;}}public void stageOne() throws InterruptedException {lock.lock();System.out.println(Thread.currentThread().getName() + " is waiting...");condition.await();System.out.println(Thread.currentThread().getName() + ", resumed.");try {increment();} finally {lock.unlock();}}public void stageTwo() {lock.lock();System.out.println(Thread.currentThread().getName() + ", click to continue!");Scanner scanner = new Scanner(System.in);scanner.nextLine();scanner.close();System.out.println(Thread.currentThread().getName() + ", enter key pressed.");condition.signal();try {increment();} finally {lock.unlock();}}public void afterRunning() {System.out.println("The count is: " + count);}
}运行结果:
Thread-0 is waiting...
Thread-1, click to continue!Thread-1, enter key pressed.
Thread-0, resumed.
The count is: 20000
4.己见
这篇关于Multi-Programming-10 Re-entrant Locks的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!