您当前的位置: 首页 >  Java

止步前行

暂无认证

  • 0浏览

    0关注

    247博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Java并发编程——自定义Lock锁

止步前行 发布时间:2019-03-30 23:56:30 ,浏览量:0

一、引言

在学习JUC并发包的时,会介绍Lock锁。为了更深入的了解Lock锁的机制,我们可以自定义一个Lock锁,这样去读Lock源码可能好理解一点。

二、自定义Lock锁 1、定义Lock接口

public interface Lock {

	class TimeOutException extends Exception {
		public TimeOutException(String message) {
			super(message);
		}
	}

	void lock() throws InterruptedException;

	void lock(long mills) throws InterruptedException, TimeOutException;

	void unlock();

	Collection getBlockedThread();

	int getBlockedSize();
}
2、Lock实现类
public class BooleanLock implements Lock {

	// 表示对象的锁是否被占用,true表示对象锁已经被占用
	private boolean initValue;

	// 表示被阻塞线程的集合
	private Collection blockedThreadCollection = new ArrayList();

	// 记录获得当前对象锁的线程
	private Thread currentThread;

	public BooleanLock() {
		this.initValue = false;
	}

	/**
	 * 加锁,使用synchronized实现同步
	 */
	@Override
	public synchronized void lock() throws InterruptedException {
		// 如果锁已经被占用,则阻塞当前线程
		while (initValue) {
			//将线程加入到阻塞线程集合
			blockedThreadCollection.add(Thread.currentThread());
			this.wait();
		}

		// 锁没有被占用,则当前线程获得锁
		blockedThreadCollection.remove(Thread.currentThread());
		this.initValue = true;
		this.currentThread = Thread.currentThread();
	}

	/**
	 * 当线程等待一定时间后,没有释放锁,则其他线程抛出超时异常
	 */
	@Override
	public synchronized void lock(long mills) throws InterruptedException, TimeOutException {
		if (mills             
关注
打赏
1657848381
查看更多评论
0.0653s