Guarded Suspension模式(确保挂起)

发现条件不满足时,就暂时挂起等待条件满足,常见的在BlockingQueue中含有大量的Guarded Suspension模式

public class GuardedSuspensionQueue<T>{

    private final LinkedList<T> queue = new LinkedList<>();

    private final int LIMIT;



    GardedSuspensionQueue(){

        LIMIT = 100;

    }



    GardedSuspensionQueue(int maxSize){

        LIMIT = maxSize

    }

    public void offer(T data) throws InterruptedException{

        synchronized(this){

            while(queue.size() >= LIMIT){

                this.wait();

            }



            queue.addLast(data);

            this.nofifyAll();

        }

    }



    public void take(){

        synchronized(this){

            while(queue.isEmpty()){

                this.wait();

            }



            this.notifyAll();

            return queue.removeFirst();

        }

    }

    

}



上面的代码可以通过This充当锁,也可以通过定义一个Object对象充当锁。

发布了115 篇原创文章 · 获赞 57 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/qq_35211818/article/details/104186407
今日推荐