1. 重入锁
重入锁使用java.util.concurrent.locks.ReentrantLock类来实现。
public class ReenterLock implements Runnable{
// 声明可重入锁,建议声明为static
public static ReentrantLock lock = new ReentrantLock();
public static int i = 0;
@Override
public void run() {
for(int j=0; j<10000000; j++) {
// 使用可重入锁保护临界资源
lock.lock();
try {
i++;
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
ReenterLock reenterLock = new ReenterLock();
Thread t1 = new Thread(reenterLock);
ReenterLock reenterLock2 = new ReenterLock();
Thread t2 = new Thread(reenterLock2);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(i);
}
}
重入锁允许多次加锁,但是与之对应的释放锁次数也要一致。