定义一个接口
public interface Lock {
public static class TimeOutExection extends Exception{
/**
*
*/
private static final long serialVersionUID = 1L;
public TimeOutExection(String message) {
super(message);
}
}
void lock() throws InterruptedException;
void lock(long mills) throws InterruptedException;
void unlock();
CollectiongetBlockThread();
int getBlockSize();
定义实现类
public class BooleanLock implements Lock{
private boolean initValue;//true锁正在被占用,需要wait等待
private Collection 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 getBlockThread() {
return Collections.unmodifiableCollection(blockThreadCollect);
}
@Override
public int getBlockSize() {
return blockThreadCollect.size();
}
定义一个测试类:
public class LockTest{
static int threadCount = 0;
public static void main(String[] args) {
List listName = new ArrayList();
for(int i =0;i<1000000;i++){
listName.add(“T”+i);
}
//模仿高并发,由于休眠2秒一百万并发量会跑30天
final BooleanLock booleanLock = new BooleanLock();
//ExecutorService executorService = Executors.newCachedThreadPool();
ExecutorService executorService = Executors.newFixedThreadPool(200);
listName.stream().forEach(name ->
executorService.submit(new Runnable(){
@Override
public void run() {
try {
booleanLock.lock();
Optional.of(Thread.currentThread().getName()+" have the lock").ifPresent(System.out::println);
work();//项目中的业务逻辑代码
Optional.of("thread running count is "+threadCount).ifPresent(System.out::println);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
booleanLock.unlock();
}
}}
)
);
executorService.shutdown();
}
private static void work() throws InterruptedException {
Optional.of(Thread.currentThread().getName()+" is working.....").ifPresent(System.out::println);
LockTest.threadCount++;
Thread.sleep(2000);
}