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);
}
}
重入鎖允許多次加鎖,但是與之對應的釋放鎖次數也要一致。