得到别的线程任务的返回值
import lombok.extern.slf4j.Slf4j; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; @Slf4j public class FutureExample { static class MyCallable implements Callable<String> { @Override public String call() throws Exception{ log.info("do something in callable"); Thread.sleep(500); return "Done"; } } public static void main(String[] args) throws Exception{ ExecutorService executorService= Executors.newCachedThreadPool(); Future<String> future= executorService.submit(new MyCallable());//提交任务 log.info("do something in main"); Thread.sleep(1000); String result=future.get(); log.info("result:{}",result); } }
import lombok.extern.slf4j.Slf4j; import java.util.concurrent.Callable; import java.util.concurrent.FutureTask; @Slf4j public class FutureTaskExample { public static void main(String[] args) throws Exception{ FutureTask<String> futureTask=new FutureTask<String>(new Callable<String>() { @Override public String call() throws Exception { log.info("do something in callable"); Thread.sleep(500); return "Done"; } }); new Thread(futureTask).start(); log.info("do something in main"); Thread.sleep(1000); String result=futureTask.get(); log.info("result:{}",result); } }
实现代码示例:
import lombok.extern.slf4j.Slf4j; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.Future; import java.util.concurrent.RecursiveTask; @Slf4j public class ForJoinTaskExample extends RecursiveTask<Integer>{ public static final int threshold=2; private int start; private int end; public ForJoinTaskExample(int start,int end){ this.start=start; this.end=end; } @Override protected Integer compute(){ int sum=0; //如果任务足够小,就计算 boolean canCompute=(end-start)<=threshold; if(canCompute){ for(int i=start;i<=end;i++){ sum+=i; } }else { //如果任务大于阀值,就分裂成两个子任务计算 int middle=(start+end)/2; ForJoinTaskExample leftTask=new ForJoinTaskExample(start,middle); ForJoinTaskExample rightTask=new ForJoinTaskExample(middle+1,end); //执行子任务 leftTask.fork(); rightTask.fork(); //等待任务执行结束合并结果 int leftResult=leftTask.join(); int rightResult=rightTask.join(); //合并子任务 sum=leftResult+rightResult; } return sum; } public static void main(String[] args) { ForkJoinPool forkJoinPool=new ForkJoinPool(); //生成一个计算任务1+2+3+4 ForJoinTaskExample task=new ForJoinTaskExample( 1,100); //执行一个任务 Future<Integer> result=forkJoinPool.submit(task); try{ log.info("result:{}",((ForkJoinTask) result).get()); }catch (Exception e){ log.error("exception",e); } } }
线程安全,用于生产消费者模式。
允许插入空对象