package com.duan.tool.utils; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; /** * @Description * 三、通过Callable和Future创建线程 * * (1)创建Callable接口的实现类,并实现call()方法,该call()方法将作为线程执行体,并且有返回值。 * * (2)创建Callable实现类的实例,使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。 * * (3)使用FutureTask对象作为Thread对象的target创建并启动新线程。 * * (4)调用FutureTask对象的get()方法来获得子线程执行结束后的返回值 * */ @Slf4j final class AccumCallable implements Callable<List<String>> { private final int begin; private final int end; private static int count=0; public AccumCallable(int begin, int end) { this.begin = begin; this.end = end; } @Override public List<String> call() throws Exception { ArrayList<String> list = new ArrayList<>(); for (int i = begin; i <end; i++) { count++; log.info("i={}",count); } return list; } }
import lombok.extern.slf4j.Slf4j; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; /** * @Description * @Author Lucky dog * @Date 2021/2/24 0024 */ @Slf4j public class TestCallable { @Test public void test(){ int count=12; // 判断导入数据,如果大于10条,使用线程插入数据 if (count > 10) { List<FutureTask<List<String>>> futureTasks = new ArrayList<>(10); int nums = count / 10; for (int i = 0; i < 10; i++) { int startIndex = nums * i; int endIndex = nums * (i + 1); if (i == 9) { endIndex = count; } int finalEndIndex = endIndex; // 创建线程任务实例 FutureTask<List<String>> futureTask = new FutureTask<>(new AccumCallable(startIndex, finalEndIndex)); // 添加任务到线程列表 futureTasks.add(futureTask); // 创建线程 Thread worker = new Thread(futureTask, "数据导入线程" + i); //开始执行任务 worker.start(); } // 获取图片名 List<String> lists = new ArrayList<>(); for (FutureTask<List<String>> futureTask : futureTasks) { int ret = 0; // get() 方法会阻塞直到获得结果 try { lists.addAll(futureTask.get()); } catch (InterruptedException e) { log.error("线程返回异常:{}", e.getMessage()); } catch (ExecutionException e) { log.error("线程返回异常:{}", e.getMessage()); } } } else { } System.out.println("我等着线程执行完后在执行哈哈哈哈哈====="); } }