为什么在这个多线程应用程序中需要单例模式?

Tom*_*han 3 java singleton multithreading

我最近遇到了两个线程陷入死锁的问题,因为它们没有按照我想象的方式监视同一个对象。事实证明,实现 Singleton 模式解决了这个问题但为什么?

我只实例化了该类的一个实例,该类的对象是私有属性,因此我希望它无论如何都是有效的单例。


为了问题的完整性,这里还有一些代码说明了差异:

在单例模式实现之前:

class Worker {
    private BlockingQueue q = new LinkedBlockingQueue();

    public void consume(String s) {
        // Called by thread 1.
        // Waits until there is anything in the queue, then consumes it
    }

    public void produce(String s) {
        // Called by thread 2.
        // Puts an object in the queue.
    }

    // Actually implements Runnable, so there's a run() method here too...
}
Run Code Online (Sandbox Code Playgroud)

线程是这样启动的:

Worker w = new Worker();
new Thread(w).start();

// Producer also implements Runnable. It calls produce on its worker.
Producer p = new Producer(w);
new Thread(p).start();
Run Code Online (Sandbox Code Playgroud)

produce()现在,当我检查和中实际使用的队列时consume()System.identityHashCode(q)在不同的线程中给出了不同的结果。

使用单例模式:

class Worker {
    private static BlockingQueue q;
    private BlockingQueue getQueue() {
        if(q == null) {
            q = new LinkedBlockingQueue();
        }
        return q;
    }
    // The rest is unchanged...
}
Run Code Online (Sandbox Code Playgroud)

突然间,它起作用了。为什么这里需要这种模式?

jbi*_*del 5

问题是您正在构造函数new Worker()内部创建一个Server。你有这个:

public Server(Worker worker) {
    this.clients = new ArrayList<ClientHandle>();
    this.worker = new Worker();  // This is the problem.


// Don't do this in the Server constructor.
this.worker = new Worker();

// Instead do this:
this.worker = worker;
Run Code Online (Sandbox Code Playgroud)