栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

线程池之阻塞主线程,等子线程全部跑完之后,执行主线程

线程池之阻塞主线程,等子线程全部跑完之后,执行主线程

在spark中有异步多线程的需求,需要阻塞主线程,等所有子线程都执行完成后,主线程继续执行。
如果是用Thread,不太好实现,用Callable+FutrueTask结合线程池,可以快速实现:

final AtomicInteger messagesReceived = new AtomicInteger(0);

// ThreadedListenerAdapter is the class that I'm testing 
// It's not germane to the question other than as a target for a thread pool.
final ThreadedListenerAdapter adapter = 
    new ThreadedListenerAdapter(listener);
int taskCount = 10;

List> taskList = new ArrayList>();

for (int whichTask = 0; whichTask < taskCount; whichTask++) {
    FutureTask futureTask = 
        new FutureTask(new Callable() {
        @Override
        public Integer call() throws Exception {
            // Does useful work that affects messagesSent
            return messagesSent;
        }
    });
    taskList.add(futureTask);
}

for (FutureTask task : taskList) {
    LocalExecutorService.getExecutorService().submit(task);
}

for (FutureTask task : taskList) {
    int result = 0;
    try {
       // 关键是这里
        result = task.get();
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    } catch (ExecutionException ex) {
        throw new RuntimeException("ExecutionException in task " + task, ex);
    }
    assertEquals(maxMessages, result);
}

int messagesSent = taskCount * maxMessages;
assertEquals(messagesSent, messagesReceived.intValue());
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/487980.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号