手写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

喜欢的点个赞谢谢!!

发布了104 篇原创文章 · 获赞 13 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/Liutt55/article/details/102767862