实现一个可重入锁

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zz0129/article/details/80892976

可重入锁为当一个线程获得该锁后若未释放前想要再次获取该锁,则可以直接获取不用等待,我们只需要把锁的次数加一即可,释放一次锁次数就减一,直到次数为零,其它线程就可以继续竞争该锁了。

package com.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class MyLock implements Lock{
	private boolean isLock = false;
	private Thread threadBy = null;
	private int threadCount = 0;
	@Override
	public synchronized void lock() {
		// TODO Auto-generated method stub
		Thread currentThread = Thread.currentThread();
		while(isLock && currentThread != threadBy){
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		isLock = true;
		threadBy = currentThread;
		threadCount++;
	}

	@Override
	public synchronized void unlock() {
		// TODO Auto-generated method stub
		if(threadBy==Thread.currentThread()){
			threadCount--;
			if(threadCount == 0){
				notify();
				isLock = false;
			}
		}
	}


	@Override
	public void lockInterruptibly() throws InterruptedException {
		// TODO Auto-generated method stub
		
	}


	@Override
	public Condition newCondition() {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public boolean tryLock() {
		// TODO Auto-generated method stub
		return false;
	}


	@Override
	public boolean tryLock(long arg0, TimeUnit arg1) throws InterruptedException {
		// TODO Auto-generated method stub
		return false;
	}

	
}

展开阅读全文

没有更多推荐了,返回首页