Callable接口具备的特征如下
1.有简单的类型参数,与call()方法的返回类型相对应
2.声明了call方法,执行器运行任务时,该方法会被执行器执行,它必须返回声明中指定类型的对象
3.call()方法可以抛出任何一种校验异常,可以实现自己的执行器重载afterExecute方法来处理这些异常
package com.java.test.callable; import lombok.extern.slf4j.Slf4j; import java.util.UUID; import java.util.concurrent.Callable; /** * @author yourheart * @Description * @create 2022-10-19 22:50 */ @Slf4j public class ThreadCallable implements Callable<String> { /** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */ @Override public String call() throws Exception { Thread.sleep(5000); log.info("call执行中..."); return UUID.randomUUID().toString(); } }
package com.java.test.callable; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * @author yourheart * @Description * @create 2022-10-19 22:51 */ @Slf4j public class CallableTest { /** * 核心线程数 */ int corePoolSize = 3; /** * 最大线程数 */ int maximumPoolSize = 6; /** * 超过 corePoolSize 线程数量的线程最大空闲时间 */ long keepAliveTime = 2; /** * 以秒为时间单位 */ TimeUnit unit = TimeUnit.SECONDS; /** * 创建工作队列,用于存放提交的等待执行任务 */ BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(2); @Test /** * 执行器测试 */ public void actuatorTest() throws ExecutionException, InterruptedException { ThreadCallable threadCallable = new ThreadCallable(); ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, new ThreadPoolExecutor.AbortPolicy()) { @Override protected void afterExecute(Runnable r, Throwable t) { /** * 当call方法中执行有错误,可以在这里处理 */ // super.afterExecute(r, t); log.info("afterExecute 任务执行结束了....:{}",t); } }; Future<String> submit = poolExecutor.submit(threadCallable); String result = submit.get(); log.info("result:{}",result); poolExecutor.shutdown(); } public void test() throws ExecutionException, InterruptedException { ThreadCallable threadCallable = new ThreadCallable(); FutureTask<String> futureTask = new FutureTask<>(threadCallable); //启动线程,执行callable的业务 new Thread(futureTask).start(); //同步等待返回结果 String result = futureTask.get(); log.info("输出线程的返回结果:{}",result); } }
标签:util,java,new,Callable,concurrent,result,简单,import,多线程 From: https://www.cnblogs.com/q202105271618/p/16808166.html