java – 在Executor服务中的ThreadPool中添加线程

我正在进行多线程程序,我正在尝试确保每个线程运行30分钟.假设我们有10个线程,那么10个线程中的每个线程应运行30分钟.

以下是我的代码 –

class ThreadTask implements Runnable {
    private final long endTime;

    public ThreadTask(long endTime) {
        this.endTime = endTime;
    }

    @Override
    public void run() {

        while (System.currentTimeMillis() <= endTime) {

            // do something meaningful

        }   
    }
}

public class TestPool {

    public static void main(String[] args) {

        // create thread pool with given size
        ExecutorService service = Executors.newFixedThreadPool(1000); 

        long startTime = System.currentTimeMillis();
        long endTime = startTime + (30 * 60 * 1000);

        for (int i = 0; i < threads; i++) {
            service.submit(new ThreadTask(endTime));
        }

        // wait for termination        
        service.shutdown();
        service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); 
    }
}

现在我的问题是 –

以上代码是否保证每个线程同时启动并运行30分钟?我不确定将线程放入线程池需要多长时间.但看起来有些线程可能会稍微延迟开始并且它们将不会运行30分钟,可能不到30分钟.

I am looking for each thread should start at same time and they should
run for exactly 30 minutes

解决方法:

简短的回答:不,所有的线程都不能完全同时启动(取决于你的容忍度,它可能’相当’可以忽略不计).并且取决于有意义的事情,每个线程运行30分钟的可能性很小(再次在这里,你的时间粒度可能会使这个断言错误).

信息:

>为了确保最大化所有线程彼此尽可能接近的机会,首先创建线程然后将其提交给执行程序.与其他语言一样,Java中的线程创建是一项昂贵的操作.
>为了让线程运行30分钟,我建议每个线程计算自己的终止时间,因为你当前传递给构造函数的参数可能已经影响了你的精度(由于线程创建时间).
>通常不推荐(除非你在怪物机器或微积分网格上运行java)创建一个包含1000个线程的线程池.请记住,如果物理机没有与线程一样多的内核,则每次JVM决定应运行哪个线程时,都会发生上下文切换.

编辑:

public class TestPool {

    public static void main(String[] args) {

        // create thread pool with given size
        ExecutorService service = Executors.newFixedThreadPool(10); 

        long startTime = System.currentTimeMillis();
        long endTime = startTime + (30 * 60 * 1000);

        ThreadTask[] threadTasks = new ThreadTask[threads];
        for (int i = 0; i < threads; i++) {
            threadTasks[i] = new ThreadTask(endTime);
        }

        for (ThreadTask tt : threadTasks) {
            service.submit(tt);
        }

        // wait for termination        
        service.shutdown();
        service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); 
    }
}
上一篇:使用ExecuterService的多个SwingWorkers无法正常工作


下一篇:java – ExecutorService – 使用特定时间限制执行每个任务