<分区>
If a Thread needs to be run more than once, then one should make an new instance of the Thread and call start on it.
这是怎么做到的?
<分区>
If a Thread needs to be run more than once, then one should make an new instance of the Thread and call start on it.
这是怎么做到的?
最佳答案
我会使用另一层抽象。使用 ExecutorService
.
这是一个简单的例子:
public static void main(String args[]) throws InterruptedException {
final ExecutorService service = Executors.newCachedThreadPool();
final class MyTask implements Runnable {
@Override
public void run() {
System.out.println("Running my task.");
}
};
for (int i = 0; i < 10; ++i) {
service.submit(new MyTask());
}
service.shutdown();
service.awaitTermination(1, TimeUnit.DAYS);
}
只需将您的任务转储到服务
中,次数不限。
ExecutorService
是一个线程池 - 它有许多 Thread
来接收任务。这消除了产生新的 Thread
的开销,因为它缓存了它们。
关于Java - 运行一个线程两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19888940/