不可重入锁:
public class LockTest01 {
Lock lock = new Lock();
public void a() throws InterruptedException{
lock.lock();
doSomething();
lock.unlock();
}
public void doSomething() throws InterruptedException {
lock.lock();
lock.unlock();
}
public static void main(String[] args) throws InterruptedException {
LockTest01 test = new LockTest01();
test.a();
test.doSomething();
}
}
class Lock{
private boolean isLocked = false;
public synchronized void lock() throws InterruptedException{
while(isLocked){
wait();
}
isLocked = true;
}
public synchronized void unlock(){
isLocked = false;
notify();
}
}
可重入锁:
public class LockTest02 {
ReLock lock = new ReLock();
public void a() throws InterruptedException{
lock.lock();
System.out.println(lock.getHoldCount());
doSomething();
lock.unlock();
System.out.println(lock.getHoldCount());
}
public void doSomething() throws InterruptedException {
lock.lock();
System.out.println(lock.getHoldCount());
lock.unlock();
System.out.println(lock.getHoldCount());
}
public static void main(String[] args) throws InterruptedException {
LockTest02 test = new LockTest02();
test.a();
Thread.sleep(1000);
System.out.println(test.lock.getHoldCount());
}
}
class ReLock{
private boolean isLocked = false;
private Thread lockedBy = null;
private int holdCount = 0;
public synchronized void lock() throws InterruptedException{
Thread t = Thread.currentThread();
while(isLocked && lockedBy!=t){
wait();
}
isLocked = true;
lockedBy = t;
holdCount++;
}
public synchronized void unlock(){
if(Thread.currentThread() == lockedBy){
holdCount--;
if(holdCount==0){
isLocked = false;
notify();
lockedBy=null;
}
}
}
public int getHoldCount() {
return holdCount;
}
}