Java高并发编程(7)
程序员文章站
2022-06-19 08:25:03
...
用synchronized、wait、notifyAll实现lock锁
直接贴代码
lock接口
public interface LockInterface {
void lock() throws InterruptedException;
void lock(long millis) throws InterruptedException, TimeoutException;
void unlock() throws IllegalAccessException;
Collection<Thread> getWaitThreads();
int getWaitSize();
}
lock的实现BooleanLock
public class BooleanLock implements LockInterface {
//加锁标志位
private boolean isLock = false;
//将等待线程放入队列,观察等待线程个数
private LinkedList<Thread> waitThreads = new LinkedList();
//防止不是加锁的线程解锁
private Thread currThread;
@Override
public synchronized void lock() throws InterruptedException {
while (isLock) {
waitThreads.add(Thread.currentThread());
wait();
waitThreads.remove(Thread.currentThread());
}
currThread = Thread.currentThread();
isLock = true; //获取锁
}
@Override
public synchronized void lock(long millis) throws InterruptedException, TimeoutException {
if (millis<=0){
lock();
}
long baseTime = System.currentTimeMillis();
while (isLock){
long currTime = System.currentTimeMillis();
if (currTime-baseTime>millis){
throw new TimeoutException("Time Out");
}
waitThreads.add(Thread.currentThread());
wait(millis);
waitThreads.remove(Thread.currentThread());
}
currThread = Thread.currentThread();
isLock = true; //获取锁
}
@Override
public synchronized void unlock() throws IllegalAccessException {
if (currThread != Thread.currentThread()){
throw new IllegalAccessException("唤醒锁权限异常");
}
isLock = false;
notifyAll();
}
@Override
public Collection<Thread> getWaitThreads() {
return Collections.unmodifiableCollection(waitThreads);
}
@Override
public int getWaitSize() {
return waitThreads.size();
}
}
测试代码
public class DEMO {
public static void main(String[] args) throws InterruptedException {
BooleanLock lock = new BooleanLock();
Thread t1 = new Thread(()->{
try {
lock.lock();
System.out.println("t1 do something");
Thread.sleep(3_000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
try {
System.out.println("t1 release");
lock.unlock();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(()->{
try {
lock.lock();
System.out.println("t2 do something");
Thread.sleep(3_000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
try {
System.out.println("t2 release");
lock.unlock();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
});
Thread t3 = new Thread(()->{
try {
lock.lock(3000);
System.out.println("t3 do something");
Thread.sleep(4_000);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
} finally {
try {
System.out.println("t3 release");
lock.unlock();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
}
}
上一篇: Spring在web开发中的应用