MySimpleLock

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();
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值