import java.util.concurrent.locks.AbstractQueuedSynchronizer;
public class MySimpleLock {
private Syn syn = new Syn();
private static class Syn extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 1L;
@Override
protected boolean tryAcquire(int acquires) {
return justTryAcquire(acquires);
}
private boolean justTryAcquire(int acquires) {
int state = super.getState();
Thread current = Thread.currentThread();
if(state==0) {
if(super.compareAndSetState(state, state+acquires)) {
setExclusiveOwnerThread(current);
return true;
}
} else if(current==getExclusiveOwnerThread()) {
if(compareAndSetState(state, state+acquires)) {
return true;
}
}
return false;
}
@Override
protected boolean tryRelease(int release) {
Thread current = Thread.currentThread();
if(current!=getExclusiveOwnerThread()) {
throw new IllegalMonitorStateException("release error");
}
int p = super.getState();
int c = p-release;
if(c==0) {
setState(c);
setExclusiveOwnerThread(null);
return true;
} else {
setState(c);
return false;
}
}
@Override
protected boolean isHeldExclusively() {
return getExclusiveOwnerThread() == Thread.currentThread();
}
}
public boolean tryLock() {
return syn.justTryAcquire(1);
}
public void lock() {
syn.acquire(1);
}
public void unlock() {
syn.release(1);
}
}
public class MySimpleLockTest {
static MySimpleLock lock = new MySimpleLock();
public static void main(String ... args) throws InterruptedException {
tryLockThread(2000, "06");
Thread.sleep(500);
lockThread(0, "01");
lockThread(0, "02");
lockThread(0, "03");
lockThread(0, "05");
lockThread(3110, "04");
}
private static void lockThread(final long time, final String name) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("locking:"+name);
lock.lock();
try {
System.out.println("enter:"+name);
Thread.sleep(time);
System.out.println("exit:"+name);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
});
thread.start();
}
private static void tryLockThread(final long time, final String name) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("trylocking:"+name);
if(lock.tryLock()) {
try {
System.out.println("enter:"+name);
Thread.sleep(time);
System.out.println("exit:"+name);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
});
thread.start();
}
}