私人订制可重入锁
话不多说,看代码!
public class MyLock implements Lock { private volatile boolean lockflag = false; private int count; private Thread threadby = null; @Override public synchronized void lock() { if(lockflag == true && threadby != Thread.currentThread()){ try { wait(); } catch (InterruptedException e) { } } lockflag = true; threadby = Thread.currentThread(); count++; } @Override public void lockInterruptibly() throws InterruptedException { } @Override public boolean tryLock() { return false; } @Override public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { return false; } @Override public synchronized void unlock() { if(threadby == Thread.currentThread()){ count--; if(count==0) { lockflag = false; notify(); } } } @Override public Condition newCondition() { return null; } }
别的都没重写,就重写了lock,unlock,不过面试够用了!