欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

基于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());
    }
}