定義一個接口
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);
}