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() {
@Override
public void run() {
try {
sharedObjectRe.stageOne();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
sharedObjectRe.stageTwo();
}
});
t1.start();
t2.start();
try {
t1.join();
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.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.己见
对于一般的功能而言,传统的synchronized关键字和re-entrant lock 可以提供相似的功能。但ReentrantLock 有更多的扩展功能可以提供,如可以有多个wait/notify队列;特有的boolean awaitUntil(Date deadline)\void awaitUninterruptedly()等问题。
相关代码和笔记可以在这里看到。