仅在队列中有内容时才消耗 cpu 的工作线程

Worker thread that only consumes cpu when there is something in the queue

这是我想要做的。

我想要一个有队列并启动线程的对象。另一个线程可以通过 object.addWork(work);

推送到该队列

这会将工作推入队列并唤醒正在休眠的线程。然后线程对队列中的每个对象执行工作,直到队列为空。

一旦队列为空并且没有剩余工作,该线程就会休眠并需要通过再次添加到队列来唤醒。

是否有线程安全的方法来创建这样的对象?

您基本上想要 Executors.newSingleThreadExecutor 可以做的事情

class YouNameIt{
    private ExecutorService executor;

    public void start(){
        executor = Executors.newSingleThreadExecutor();
    }

    public void put(Object o){
        executor.submit(new Runnable() {
            @Override
            public void run() {
                process(o);
            }
        });
    }

    private void process(Object o) {
        //Put your processing here
    }

    public void stop(){
        executor.shutdown();
    }
}