ReentrantLock和synchronized的作用类似,都是可以处理多线程下的同步问题,但是ReentrantLock比synchronized有一定的优势,比如可以指定获取锁的等待时间,如果超时则进行其他操作,不用一直等待下去。
示例代码:
public class TestClass {
private final Lock lock = new ReentrantLock();
private int count;
public void add() {
try {
if(lock.tryLock(1, TimeUnit.SECONDS)){
lock.lock();
try {
for (int i = 0; i < 5; i++) {
count ++;
System.out.println("Test ReentrantLock "+count);
}
Thread.sleep(3000);
} finally {
lock.unlock();
}
}else {
System.out.println("Test ReentrantLock timeout");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class MyClass {
public static void main(String[] args) {
final TestClass testClass = new TestClass();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Test ReentrantLock Thread A running");
testClass.add();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Test ReentrantLock Thread B running");
testClass.add();
}
}).start();
}
}
运行结果: