Java:如何按需唤醒线程? [英] Java: How to wake thread on demand?
问题描述
假设我想创建一个基本上无限运行线程的对象.我希望线程在不需要他的情况下进入睡眠状态,但是当需要完成某些工作时,它将唤醒线程-完成工作并返回睡眠状态.我还希望将作业排入队列并按它们到达的顺序执行.在可可/目标c中,有一个NSOperationQueue.我不知道Java是否有类似的东西.
Let's say I want to create an object that basically runs a thread infinitely. I want the thread to sleep while there is no need for him, but when there is a need for certain job to be done, it wakes the thread - gets the job done and goes back to sleep. I also want the jobs to be queued and be executed in the order they arrive. In cocoa/objective c there is an NSOperationQueue for that. I wonder if java has something similar.
您怎么看?
推荐答案
我会使用ExecutorService之类的
I would use an ExecutorService like
private final ExecutorService executor = Executors.newSingleThreadExecutor();
public void task(final int arg) {
executor.execute(new Runnable() {
@Override
public void run() {
// perform task using `arg`
}
});
}
该线程具有一个内置线程,该线程在添加任务时唤醒,在没有剩余任务时进入睡眠状态,这是队列任务的阻塞队列.
This has a built in thread which wakes when a tasks is added and sleeps when there is no tasks left, a Blocking Queue for queue tasks.
这篇关于Java:如何按需唤醒线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!