等到所有线程在 java 中完成它们的工作 [英] wait until all threads finish their work in java

查看:29
本文介绍了等到所有线程在 java 中完成它们的工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应用程序,它有 5 个线程,可以同时从 Web 获取一些信息,并在缓冲区类中填充 5 个不同的字段.
我需要在所有线程完成工作后验证缓冲区数据并将其存储在数据库中.
我该怎么做(当所有线程完成工作时收到警报)?

I'm writing an application that has 5 threads that get some information from web simultaneously and fill 5 different fields in a buffer class.
I need to validate buffer data and store it in a database when all threads finished their job.
How can I do this (get alerted when all threads finished their work) ?

推荐答案

我采用的方法是使用 ExecutorService 来管理线程池.

The approach I take is to use an ExecutorService to manage pools of threads.

ExecutorService es = Executors.newCachedThreadPool();
for(int i=0;i<5;i++)
    es.execute(new Runnable() { /*  your task */ });
es.shutdown();
boolean finished = es.awaitTermination(1, TimeUnit.MINUTES);
// all tasks have finished or the time has been reached.

这篇关于等到所有线程在 java 中完成它们的工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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