监控队列 - ConcurrentLinkedQueue?

Monitor queue - ConcurrentLinkedQueue?

我想实现一个监视器队列,两个不相关的线程可以共享它。在这种情况下仅使用 ConcurrentLinkedQueue 是否足够,还是我应该以不同的方式使用?我想实现活动对象设计模式并且有 ActivationQueue - 它是普通的 Java 队列,必须作为监视器对象实现,因为模式的其他组件添加到队列中。

如果你需要thread-safe Queue, ConcurrentLinkedQueue could be enough for you but if you rather need a thread-safe BlockingQueue, you should use a LinkedBlockingQueue instead for such need like the example of implementation of the pattern Active Object on wikipedia.

class OriginalClass {

    private double val = 0.0;

    void doSomething() {
        val = 1.0;
    }

    void doSomethingElse() {
        val = 2.0;
    }
}

class BecomeActiveObject {

    private double val = 0.0;

    private BlockingQueue<Runnable> dispatchQueue = new LinkedBlockingQueue<Runnable>();

    public BecomeActiveObject() {
        new Thread (new Runnable() {

                @Override
                public void run() {
                    while(true) {
                        try {
                            dispatchQueue.take().run();
                        } catch (InterruptedException e) {   
                            // okay, just terminate the dispatcher
                        }
                    }
                }
            }
        ).start();
    }

    //
    void doSomething() throws InterruptedException {
        dispatchQueue.put(new Runnable() {
                @Override
                public void run() { 
                    val = 1.0; 
                }
            }
        );
    }

    //
    void doSomethingElse() throws InterruptedException {
        dispatchQueue.put(new Runnable() {
                @Override
                public void run() { 
                    val = 2.0; 
                }
            }
        );
    }
}