public class TestReentrantLock{
public static void main(String[] args) {
Lock2 lock2 = new Lock2();
new Thread(lock2).start();
new Thread(lock2).start();
new Thread(lock2).start();
}
}
class Lock2 implements Runnable{
int num = 10;
// 定义锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try {
lock.lock();// 加锁
if (num>0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(num--);
}else {
break;
}
}finally {
lock.unlock();// 解锁
}
}
}
}
ReentrantLock锁相比于synchronized在jvm里面消耗更少,所以更推荐使用ReentrantLock。