手写java高并发Lock、unLock实现线程安全,干净又卫生非常刺激。

1.写一个接口
import java.util.Collection;

public interface Lock {

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

void lock() throws InterruptedException;

void lock(long mills) throws InterruptedException;

void unlock();

Collection<Thread>getBlockThread();

int getBlockSize();

}
2.写一个实现类
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

public class BooleanLock implements Lock{

private boolean initValue;//true锁正在被占用,需要wait等待

private Collection<Thread> blockThreadCollect = new ArrayList<>();

private Thread currentThread;//定义一个当前线程变量


public BooleanLock() {
	this.initValue = false;
}
@Override
public synchronized void lock() throws InterruptedException {
	while(initValue) {
		this.wait();
		blockThreadCollect.add(Thread.currentThread());//加入队列
	}
	blockThreadCollect.remove(Thread.currentThread());
	this.initValue = true;
	this.currentThread = Thread.currentThread();
}

@Override
public synchronized void lock(long mills) throws InterruptedException {
	if(mills <= 0) {
		lock();
		long hasRemaining = mills;
		long endTime = System.currentTimeMillis()+mills;
		while(initValue) {
			if(hasRemaining<=0) 
				throw new RuntimeException("Time out");//lock超时
			blockThreadCollect.add(Thread.currentThread());//加入队列
			this.wait(mills);
			hasRemaining = endTime - System.currentTimeMillis();
		}
		this.initValue = true;
		this.currentThread = Thread.currentThread();
	}
}

@Override
public synchronized void unlock() {
	//只能由当前线程解锁,防止被乱解锁
	if(Thread.currentThread() == currentThread) {
		this.initValue = false;
		System.out.println(Thread.currentThread().getName()+"  is release");
		this.notifyAll();
	}
}

@Override
public Collection<Thread> getBlockThread() {
	return Collections.unmodifiableCollection(blockThreadCollect);
}

@Override
public int getBlockSize() {
	return blockThreadCollect.size();
}

}
3.写一个测试类
public class LockTest {

public static void main(String[] args) {
	//模仿高并发
	final BooleanLock booleanLock = new BooleanLock();
	Stream.of("T1","T2","T3","T4","T5").forEach(name -> 
	new Thread(()->{
		try {
			booleanLock.lock();
			Optional.of(Thread.currentThread().getName()+" have the lock").ifPresent(System.out::println);
			work();//项目中的业务逻辑代码
		} catch (InterruptedException e) {
			e.printStackTrace();
		}finally {
			booleanLock.unlock();
		}
	},name).start()
	);
}

private static void work() throws InterruptedException {
	Optional.of(Thread.currentThread().getName()+" is working.....").ifPresent(System.out::println);
	Thread.sleep(5000);
}

}
测试结果:
T1 have the lock
T1 is working…
T1 is release
T5 have the lock
T5 is working…
T5 is release
T2 have the lock
T2 is working…
T2 is release
T4 have the lock
T4 is working…
T4 is release
T3 have the lock
T3 is working…
T3 is release

喜欢的点个赞谢谢!!

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值