package com.demo.config;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
/**
* @author hutf
* @createTime 2022年08月28日 16:40:00
*/
public class RecursiveActionImpl extends RecursiveAction {
private static final long serialVersionUID = 1L;
// 定义一个分解任务的阈值——50,即一个任务最多承担50个工作量
private int THRESHOLD = 5;
// 任务量
private int task_Num = 0;
private List<String> task_List;
RecursiveActionImpl(int Num) {
this.task_Num = Num;
}
public RecursiveActionImpl(List<String> task_List) {
this.task_List = task_List;
this.task_Num = task_List.size();
}
@Override
protected void compute() {
if (task_Num <= THRESHOLD) {
System.out.println(
Thread.currentThread().getName() + "承担了" + task_Num + "份工作");
try {
for (String s : task_List) {
System.out.println(Thread.currentThread().getName() + " 正执行" + s);
}
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
// // 随机解成两个任务
// Random m = new Random();
// int x = m.nextInt(THRESHOLD);
//
// ForkJoinPoolBatch left = new ForkJoinPoolBatch(x);
// ForkJoinPoolBatch right = new ForkJoinPoolBatch(task_Num - x);
//
// left.fork();
// right.fork();
// 随机解成两个任务
Random m = new Random();
int x = m.nextInt(THRESHOLD);
List<String> leftTask = task_List.subList(0, x);
List<String> rightTask = task_List.subList(x, task_List.size());
RecursiveActionImpl left = null;
RecursiveActionImpl right = null;
if (leftTask.size() > 0) left = new RecursiveActionImpl(leftTask);
if (rightTask.size() > 0) right = new RecursiveActionImpl(rightTask);
if (left != null) left.fork();
if (right != null) right.fork();
}
}
public static void main(String[] args) throws Exception {
List<String> list = new ArrayList<>();
for (int i = 0; i < 100; i++) {
String s = UUID.randomUUID().toString().replaceAll("-", "");
list.add(String.format("INSERT INTO `db_0`.`user` (`id`, `name`) VALUES (\'%s\', \'%s\') ", s, "name" + i));
}
// 创建一个支持分解任务的线程池ForkJoinPool
ForkJoinPool pool = new ForkJoinPool(1);
RecursiveActionImpl task = new RecursiveActionImpl(list);
pool.submit(task);
// pool.awaitTermination(1, TimeUnit.SECONDS);// 等待20s,观察结果
pool.shutdown();
}
}
不带返回值的多线程执行任务
于 2022-08-28 16:46:47 首次发布