Java实现主进程等待其他进程
大多采用多路复用模型,最后由主线程进行数据汇总,分支线程进行接口调用,数据库查询等耗时操作
使用Future并发
Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过get方法获取执行结果,该方法会阻塞直到任务返回结果。
- 代码
package Test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ThreadPoolTest {
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newCachedThreadPool();
Future<Integer> submit1 = executorService.submit(() -> ThreadPoolTest.trySleepInt());
Future<Integer> submit2 = executorService.submit(() -> ThreadPoolTest.trySleepInt());
Future<Integer> submit3 = executorService.submit(() -> new Integer("9"));
System.out.println(1);
// 这里要是不用get会不进入阻塞状态,主程序直接向下执行
System.out.println(submit1.get());
System.out.println(2);
System.out.println(submit2.get());
System.out.println(submit3.get());
System.out.println(3);
executorService.shutdown();
}
public static int trySleepInt(){
try {
Thread.sleep(5000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 10;
}
}
- 输出
1
10
2
10
9
3
使用CountDownLatch
CountDownLatch是一个同步工具类,用来协调多个线程之间的同步,或者说起到线程之间的通信(而不是用作互斥的作用)。
CountDownLatch能够使一个线程在等待另外一些线程完成各自工作之后,再继续执行。使用一个计数器进行实现。计数器初始值为线程的数量。当每一个线程完成自己任务后,计数器的值就会减一。当计数器的值为0时,表示所有的线程都已经完成一些任务,然后在CountDownLatch上等待的线程就可以恢复执行接下来的任务。
- 代码
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
public class demo01 {
public static void main(String[] args) throws InterruptedException {
//子线程每调用一次countDown,这个数值便会减一
CountDownLatch countDownLatch = new CountDownLatch(3);
ArrayList<Runner> runners = new ArrayList<>();
for (int i = 0; i < 3; i++) {
Runner runner = new Runner(countDownLatch);
runner.start();
runners.add(runner);
}
System.out.println("ready?");
//当CountDownLatch的计数器到0的时候会继续往下执行
countDownLatch.await();
System.out.println("Go!");
}
}
class Runner extends Thread {
private final CountDownLatch countDownLatch;
public Runner(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try {
Thread.sleep(1000 * 5);
} catch (InterruptedException e) {
System.out.println("Error " + e.getMessage());
}
System.out.println(Thread.currentThread().getName() + " had ready! Waiting other runners.");
countDownLatch.countDown();
System.out.println(Thread.currentThread().getName() + " GO!");
}
}
- 结果
ready?
Thread-2 had ready! Waiting other runners.
Thread-0 had ready! Waiting other runners.
Thread-0 GO!
Thread-1 had ready! Waiting other runners.
Thread-2 GO!
Go!
Thread-1 GO!
##参考
https://www.cnblogs.com/Lee_xy_z/p/10470181.html