Java - 运行两次线程 [英] Java - Running a thread twice

查看:117
本文介绍了Java - 运行两次线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自其他帖子


如果一个线程需要多次运行,那么应该创建一个
线程的新实例并在其上调用start。

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

I would use another layer of abstraction. Use an 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);
}

只需将您的任务转储到服务你想要的次数。

Just dump your task into the service as many times as you want.

ExecutorService 是一个线程池 - 它有一个数字 Thread 的任务,它们可以随时执行任务。这消除了产生新的 Thread 的开销,因为它会缓存它们。

The ExecutorService is a thread pool - it has a number of Threads that take tasks as they come. This removes the overhead of spawning new Threads because it caches them.

这篇关于Java - 运行两次线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆