标签: executorservice

如何使用ExecutorService等待所有线程完成?

我需要一次执行4个任务,如下所示:

ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
    taskExecutor.execute(new MyTask());
}
//...wait for completion somehow
Run Code Online (Sandbox Code Playgroud)

一旦完成所有内容,我该如何收到通知?现在我想不出比设置一些全局任务计数器更好的事情,并在每个任务结束时减少它,然后在无限循环中监视这个计数器变为0; 或获得一个Futures列表,并在无限循环监视器isDone中为所有这些.什么是更好的解决方案不涉及无限循环?

谢谢.

java parallel-processing concurrency multithreading executorservice

362
推荐指数
11
解决办法
30万
查看次数

Java Timer vs ExecutorService?

我有代码,我在那里安排任务使用java.util.Timer.我环顾四周,看到ExecutorService可以做同样的事情.所以这个问题,你有没有使用Timer和Timer计划任务,一个人使用另一个人的好处是什么?

还想检查是否有人使用过该ExecutorService课程并遇到了Timer为他们解决的任何问题.

java scheduling timer scheduled-tasks executorservice

256
推荐指数
6
解决办法
10万
查看次数

命名ExecutorService的线程和线程池

假设我有一个利用Executor框架的应用程序

Executors.newSingleThreadExecutor().submit(new Runnable(){
    @Override
    public void run(){
        // do stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

当我在调试器中运行此应用程序时,将使用以下(默认)名称创建一个线程:Thread[pool-1-thread-1].正如您所看到的,这不是非常有用,据我所知,该Executor框架没有提供一种简单的方法来命名创建的线程或线程池.

那么,如何为线程/线程池提供名称呢?例如,Thread[FooPool-FooThread].

java executorservice threadpool runnable managedthreadfactory

206
推荐指数
16
解决办法
11万
查看次数

处理Java ExecutorService任务中的异常

我正在尝试使用Java的ThreadPoolExecutor类来运行具有固定数量线程的大量重量级任务.每个任务都有许多地方,在这些地方可能因异常而失败.

我已经进行了子类化,ThreadPoolExecutor并且我已经覆盖了该afterExecute方法,该方法应该在运行任务时提供任何未捕获的异常.但是,我似乎无法使其发挥作用.

例如:

public class ThreadPoolErrors extends ThreadPoolExecutor {
    public ThreadPoolErrors() {
        super(  1, // core threads
                1, // max threads
                1, // timeout
                TimeUnit.MINUTES, // timeout units
                new LinkedBlockingQueue<Runnable>() // work queue
        );
    }

    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        if(t != null) {
            System.out.println("Got an error: " + t);
        } else {
            System.out.println("Everything's fine--situation normal!");
        }
    }

    public static void main( String [] args) {
        ThreadPoolErrors threadPool = new …
Run Code Online (Sandbox Code Playgroud)

java multithreading exception executorservice threadpoolexecutor

201
推荐指数
6
解决办法
15万
查看次数

在ExecutorService的提交和ExecutorService的执行之间进行选择

如果返回的值不是我关注的话,我应该如何在ExecutorService的 提交执行之间进行选择?

如果我同时测试两者,除了返回值之外,我没有看到两者之间有任何差异.

ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
threadExecutor.execute(new Task());
Run Code Online (Sandbox Code Playgroud)
ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
threadExecutor.submit(new Task());
Run Code Online (Sandbox Code Playgroud)

java multithreading executorservice

187
推荐指数
5
解决办法
9万
查看次数

ExecutorService,如何等待所有任务完成

等待ExecutorService完成所有任务的最简单方法是什么?我的任务主要是计算,所以我只想运行大量的工作 - 每个核心一个.现在我的设置如下:

ExecutorService es = Executors.newFixedThreadPool(2);
for (DataTable singleTable : uniquePhrases) {   
    es.execute(new ComputeDTask(singleTable));
}
try{
    es.wait();
} 
catch (InterruptedException e){
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

ComputeDTask实现runnable.这似乎正确执行任务,但代码崩溃wait()IllegalMonitorStateException.这很奇怪,因为我玩了一些玩具示例,它似乎工作.

uniquePhrases包含数万个元素.我应该使用其他方法吗?我正在寻找尽可能简单的东西

java multithreading executorservice threadpool

186
推荐指数
9
解决办法
18万
查看次数

146
推荐指数
7
解决办法
10万
查看次数

如何从线程池中获取线程ID?

我有一个固定的线程池,我提交任务(限于5个线程).如何找出这5个线程中的哪一个执行我的任务(类似"线程#3 of 5正在执行此任务")?

ExecutorService taskExecutor = Executors.newFixedThreadPool(5);

//in infinite loop:
taskExecutor.execute(new MyTask());
....

private class MyTask implements Runnable {
    public void run() {
        logger.debug("Thread # XXX is doing this task");//how to get thread id?
    }
}
Run Code Online (Sandbox Code Playgroud)

java multithreading executorservice threadpool executors

127
推荐指数
3
解决办法
18万
查看次数

无法制作具有大小限制的缓存线程池?

似乎不可能创建一个缓存的线程池,它可以创建的线程数限制.

以下是在标准Java库中实现静态Executors.newCachedThreadPool的方法:

 public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}
Run Code Online (Sandbox Code Playgroud)

因此,使用该模板继续创建固定大小的缓存线程池:

new ThreadPoolExecutor(0, 3, 60L, TimeUnit.SECONDS, new SynchronusQueue<Runable>());
Run Code Online (Sandbox Code Playgroud)

现在,如果你使用它并提交3个任务,一切都会好的.提交任何进一步的任务将导致被拒绝的执行异常.

试试这个:

new ThreadPoolExecutor(0, 3, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runable>());
Run Code Online (Sandbox Code Playgroud)

将导致所有线程按顺序执行.即,线程池永远不会有多个线程来处理您的任务.

这是ThreadPoolExecutor的execute方法中的错误?或者这可能是故意的?还是有其他方式?

编辑:我想要一些与缓存线程池完全相同的东西(它根据需要创建线程,然后在一些超时后杀死它们)但是它可以创建的线程数量受到限制,并且一旦有了它就能够继续排队其他任务达到了它的线程限制.根据sjlee的回应,这是不可能的.查看ThreadPoolExecutor的execute()方法确实是不可能的.我需要继承ThreadPoolExecutor并覆盖execute(),就像SwingWorker一样,但SwingWorker在其execute()中所做的是一个完整的hack.

java concurrency multithreading executorservice threadpoolexecutor

118
推荐指数
5
解决办法
5万
查看次数

ExecutorService在超时后中断任务

我正在寻找一个可以提供超时的ExecutorService实现.提交给ExecutorService的任务如果花费的时间超过运行超时,则会中断.实现这样的野兽不是一项艰巨的任务,但我想知道是否有人知道现有的实施.

以下是我根据下面的一些讨论提出的内容.任何意见?

import java.util.List;
import java.util.concurrent.*;

public class TimeoutThreadPoolExecutor extends ThreadPoolExecutor {
    private final long timeout;
    private final TimeUnit timeoutUnit;

    private final ScheduledExecutorService timeoutExecutor = Executors.newSingleThreadScheduledExecutor();
    private final ConcurrentMap<Runnable, ScheduledFuture> runningTasks = new ConcurrentHashMap<Runnable, ScheduledFuture>();

    public TimeoutThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, long timeout, TimeUnit timeoutUnit) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
        this.timeout = timeout;
        this.timeoutUnit = timeoutUnit;
    }

    public TimeoutThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, long timeout, …
Run Code Online (Sandbox Code Playgroud)

java concurrency multithreading executorservice

87
推荐指数
3
解决办法
9万
查看次数