废话不多说,直接上代码
实体类
package Test.TestDemo.Control.model;
public class User {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
public User() {
super();
}
}
package Test.TestDemo.Control.多线程.ForkJoin;
import Test.TestDemo.Control.model.User;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;
public class ForkJoinInsertEntity extends RecursiveAction {
private static final int THRESHOLD = 10;
private List<User> userList;
private UserMapper userMapper;
public ForkJoinInsertEntity(List<User> userList, UserMapper userMapper) {
this.userList = userList;
this.userMapper = userMapper;
}
@Override
protected void compute() {
boolean compute = userList.size() <= THRESHOLD;
if(compute){
userMapper.saveBatch(userList);
}else{
List<List<User>> lists = averageAssign(userList, 2);
ForkJoinInsertEntity task1 = new ForkJoinInsertEntity(lists.get(0), userMapper);
ForkJoinInsertEntity task2 = new ForkJoinInsertEntity(lists.get(1), userMapper);
invokeAll(task1,task2);
}
}
public static <T> List<List<T>> averageAssign(List<T> source, int n) {
List<List<T>> result = new ArrayList<>();
int remainder = source.size() % n;
int number = source.size() / n;
int offset = 0;
for (int i = 0; i < n; i++) {
List<T> value;
if (remainder > 0) {
value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
remainder--;
offset++;
} else {
value = source.subList(i * number + offset, (i + 1) * number + offset);
}
result.add(value);
}
return result;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
UserMapper userMapper = null;
LinkedList<User> userLinkedList = new LinkedList<>();
for (int i = 0; i < 1000; i++) {
User user = new User();
user.setId(i);
user.setAge(i);
user.setName("task:"+i);
userLinkedList.add(user);
}
ForkJoinPool forkJoinPool = new ForkJoinPool(10);
try {
ForkJoinInsertEntity forkJoinInsertEntity = new ForkJoinInsertEntity(userLinkedList,userMapper);
ForkJoinTask<Void> submit = forkJoinPool.submit(forkJoinInsertEntity);
submit.get();
}catch (Exception e){
e.printStackTrace();
}finally {
forkJoinPool.shutdown();
}
}
}
完结!