并发编程与高并发解决方案学习(J.U.C之Future、FutureTask、ForkJoin)

Callable与Runnable接口对比

Future接口

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 {

        @Override
        public String call() throws Exception {
            log.info("do something in callable");
            Thread.sleep(5000);
            return "Done";
        }
    }

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Future future = executorService.submit(new MyCallable());
        log.info("do something in main");
        //Thread.sleep(10000);
        log.info("这里不阻塞,可以继续异步执行");
        String result = future.get(); //get方法会发生阻塞,如果判断任务是否执行完成使用isDone()方法
        log.info("result:{}", result);
    }
}
注释掉25行
22:17:05.399 [main] INFO com.example.demo.FutureExample - do something in main
22:17:05.403 [main] INFO com.example.demo.FutureExample - 这里不阻塞,可以继续异步执行
22:17:05.407 [pool-1-thread-1] INFO com.example.demo.FutureExample - do something in callable
22:17:10.408 [main] INFO com.example.demo.FutureExample - result:Done

打开25行

22:20:54.836 [main] INFO com.example.demo.FutureExample - do something in main
22:20:54.839 [pool-1-thread-1] INFO com.example.demo.FutureExample - do something in callable
22:21:04.839 [main] INFO com.example.demo.FutureExample - 这里不阻塞,可以继续异步执行
22:21:04.839 [main] INFO com.example.demo.FutureExample - result:Done

FutureTask

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 futureTask = new FutureTask(new Callable() {
            @Override
            public String call() throws Exception {
                log.info("do something in callable");
                Thread.sleep(5000);
                return "Done";
            }
        });

        new Thread(futureTask).start();
        log.info("do something in main");
        Thread.sleep(1000);
        String result = futureTask.get();
        log.info("result:{}", result);
    }
}

22:18:55.251 [Thread-0] INFO com.example.demo.FutureTaskExample - do something in callable
22:18:55.251 [main] INFO com.example.demo.FutureTaskExample - do something in main
22:19:00.254 [main] INFO com.example.demo.FutureTaskExample - result:Done

使用场景

    在网上进行购物的时候,当看中某一件商品时,就可以提交订单,当订单处理完毕,便可以在家里等待商品送货上门,卖家根据订单从库房里取货,并配送到客户手中,客户可以在提交订单完毕继续做自己的工作,不必一直等待商品配送到手里。

模拟一段长时间任务

import java.util.concurrent.Callable;

public class RealData implements Callable {
    private String para;
    public RealData(String para){
    	this.para=para;
    }
	@Override
	public String call() throws Exception {
    	
    	StringBuffer sb=new StringBuffer();
        for (int i = 0; i < 10; i++) {
        	sb.append(para);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
            }
        }
        return sb.toString();
	}
}

模拟主任务

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
    	//构造FutureTask
        FutureTask future = new FutureTask(new RealData("a"));
        ExecutorService executor = Executors.newFixedThreadPool(1);
        //执行FutureTask,相当于上例中的 client.request("a") 发送请求
        //在这里开启线程进行RealData的call()执行
        executor.submit(future);
        System.out.println("请求完毕");
        try {
        //这里依然可以做额外的数据操作,这里使用sleep代替其他业务逻辑的处理
            Thread.sleep(2000);
        } catch (InterruptedException e) {
        }
        //相当于上例中得data.getContent(),取得call()方法的返回值
        //如果此时call()方法没有执行完成,则依然会等待
        System.out.println("数据 = " + future.get());
    }
}

我们可以看出,主任务在做长时间等待的子任务的时候,不需要再那里一直死等,而是可以继续做自己的工作,当线程执行完毕的时候,通过FutureTask的get方法获取到子任务的返回值即可。

ForkJoin

并发编程与高并发解决方案学习(J.U.C之Future、FutureTask、ForkJoin)_第1张图片

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

@Slf4j
public class ForkJoinTaskExample extends RecursiveTask {

    public static final int threshold = 2;
    private int start;
    private int end;

    public ForkJoinTaskExample(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;
            ForkJoinTaskExample leftTask = new ForkJoinTaskExample(start, middle);
            ForkJoinTaskExample rightTask = new ForkJoinTaskExample(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
        ForkJoinTaskExample task = new ForkJoinTaskExample(1, 100);

        //执行一个任务
        Future result = forkjoinPool.submit(task);

        try {
            log.info("result:{}", result.get());
        } catch (Exception e) {
            log.error("exception", e);
        }
    }
}

你可能感兴趣的:(并发编程,Java并发编程)