package com.fh.interview; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.AbstractQueuedSynchronizer; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; /** * 同步队列测试类 * * @author * @create 2018-06-02 上午10:58 **/ public class Mutex implements Lock,Serializable { private static class Sync extends AbstractQueuedSynchronizer{ @Override protected boolean tryAcquire(int arg) { assert arg == 1; if(compareAndSetState(0,1)){ setExclusiveOwnerThread(Thread.currentThread()); return true; } return false; } @Override protected boolean tryRelease(int arg) { assert arg == 1; if(getState()==0) throw new IllegalStateException(); setExclusiveOwnerThread(null); setState(0); return true; } //是否被当前线程所独占 @Override protected boolean isHeldExclusively() { return getState() == 1; } Condition newCondition(){ return new ConditionObject(); } private void readObject(ObjectInputStream s)throws IOException,ClassNotFoundException{ s.defaultReadObject(); setState(0); } } private final Sync sync = new Sync(); public void lock() { sync.acquire(1); } public void lockInterruptibly() throws InterruptedException { sync.acquireInterruptibly(1); } public boolean tryLock() { return sync.tryAcquire(1); } public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { return sync.tryAcquireNanos(1,unit.toNanos(time)); } public void unlock() { sync.release(1); } public Condition newCondition() { return sync.newCondition(); } }
测试代码
package com.fh.interview; /** * 测试 * * @author * @create 2018-06-02 上午11:22 **/ public class MutexDemo { private static final Mutex mutex = new Mutex(); public static void main(String[] args) { for (int i =0;i<10;i++){ Thread thread = new Thread(new Runnable() { @Override public void run() { mutex.lock(); try { Thread.sleep(3000); }catch (Exception e){ e.printStackTrace(); }finally { mutex.unlock(); } } },"hi"+i); thread.start(); } } }