package com.monkeylessey.utils;
|
|
import javax.validation.constraints.NotNull;
|
import java.util.ArrayList;
|
import java.util.List;
|
import java.util.concurrent.Callable;
|
import java.util.concurrent.CountDownLatch;
|
import java.util.concurrent.ExecutionException;
|
import java.util.concurrent.FutureTask;
|
import java.util.stream.Collectors;
|
|
/**
|
* @author xp
|
* @data 2023/11/4
|
*/
|
public class ThreadUtil {
|
|
/**
|
* 等待所有线程执行完成
|
*
|
* @throws InterruptedException
|
*/
|
public static void waitAllFinish() throws InterruptedException {
|
int threadCount = 5;
|
CountDownLatch latch = new CountDownLatch(threadCount);
|
for (int i = 0; i < threadCount; i++) {
|
Thread thread = new Thread(new WorkThread(latch));
|
thread.start();
|
}
|
latch.await(); // 等待所有线程执行完成
|
|
// 所有线程执行完成后继续执行其他操作
|
System.out.println("All threads have finished execution.");
|
}
|
|
|
|
static class WorkThread implements Runnable {
|
private final CountDownLatch latch;
|
|
public WorkThread(CountDownLatch latch) {
|
this.latch = latch;
|
}
|
|
@Override
|
public void run() {
|
// 执行相应的任务
|
try {
|
Thread.sleep(1000); // 模拟任务执行时间
|
System.out.println("Thread finished: " + Thread.currentThread().getName());
|
} catch (InterruptedException e) {
|
e.printStackTrace();
|
}
|
|
latch.countDown(); // 任务完成时将计数器减一
|
}
|
}
|
|
/**
|
* 获取线程执行结果
|
*
|
* @throws ExecutionException
|
* @throws InterruptedException
|
*/
|
public void runThreadAndGetResult() throws ExecutionException, InterruptedException {
|
Callable<Integer> callable = new MyCallable();
|
FutureTask<Integer> futureTask = new FutureTask<>(callable);
|
|
Thread thread = new Thread(futureTask);
|
thread.start();
|
|
// 获取线程的执行结果
|
int result = futureTask.get();
|
System.out.println("Thread result: " + result);
|
}
|
|
static class MyCallable implements Callable<Integer> {
|
@Override
|
public Integer call() throws Exception {
|
// 执行相应的任务,并返回结果
|
int result = 0;
|
for (int i = 1; i <= 10; i++) {
|
result += i;
|
}
|
return result;
|
}
|
}
|
|
/**
|
* 等待所有任务执行完成,获取执行结果
|
*
|
* @throws InterruptedException
|
* @throws ExecutionException
|
*/
|
public void waitAllFinishAndGetResult() throws InterruptedException, ExecutionException {
|
List<FutureTask<Integer>> resultList = new ArrayList<>(5);
|
List<Integer> data = new ArrayList<>(5);
|
int threadCount = 5;
|
for (int i = 0; i < threadCount; i++) {
|
Callable<Integer> callable = new MyCallable();
|
FutureTask<Integer> futureTask = new FutureTask<>(callable);
|
Thread thread = new Thread(futureTask);
|
thread.start();
|
// 不能直接调用Future的get方法,否则就变成串行执行了,失去多线程意义
|
resultList.add(futureTask);
|
}
|
for (FutureTask<Integer> futureTask : resultList) {
|
data.add(futureTask.get());
|
}
|
// 所有线程执行完成后继续执行其他操作
|
System.out.println("All threads have finished execution.");
|
System.out.println("执行结果:" + data);
|
}
|
|
}
|