基于LockSupport实现FIFO队列
程序员文章站
2024-03-18 11:51:46
...
LockSupport类中包含有实现FIFO队列的例子,可以借鉴。
public class FIFOMutext {
private AtomicBoolean locked = new AtomicBoolean(false);
private Queue<Thread> waiter = new ConcurrentLinkedQueue<>();
public void lock(){
boolean wasInterrupted = false;
Thread current = Thread.currentThread();
waiter.add(current);
while (waiter.peek() != current || !locked.compareAndSet(false, true)){
LockSupport.park(this);
if(Thread.interrupted()){
wasInterrupted = true;
}
}
waiter.remove();
if(wasInterrupted){
current.interrupt();
}
}
public void unLock(){
locked.set(false);
LockSupport.unpark(waiter.peek());
}
}
上一篇: 用两个栈实现队列
下一篇: 1014 Waiting in Line