天天看点

Java多线程-Callable和Future

一)Callable和Future简介

1、Callable简介

Callable是一个函数式接口,它只包含一个call()方法,并支持泛型。Callable是一个返回结果并且可能抛出异常的任务。

package java.util.concurrent;

@FunctionalInterface
public interface Callable<V> {
    V call() throws Exception;
}
           

2、Future简介

Future是一个接口,表示异步计算的结果。提供方法来检查计算是否完成,等待其完成,并检索计算结果。 结果只能在计算完成后使用方法get进行检索,如有必要,阻塞,直到准备就绪。 取消由cancel方法执行。

package java.util.concurrent;

public interface Future<V> {

    // 尝试取消执行此任务。
    boolean cancel(boolean mayInterruptIfRunning);

    // 如果此任务在正常完成之前被取消,则返回true。
    boolean isCancelled();

    // 返回true, 如果任务已完成
    boolean isDone();

    // 等待计算完成,然后检索其结果。
    V get() throws InterruptedException, ExecutionException;

    // 如果需要等待最多在给定的时间计算完成,然后检索其结果(如果可用)。
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
           

二)示例源码

第一步:创建一个Callable<String>类,返回值为String

import java.util.concurrent.Callable;

public class StringArgs implements Callable<String> {
	
    private String args;
    public StringArgs(String args) {
        this.args = args;
    }

    @Override
    public String call() throws Exception {
        // 执行业务逻辑
        System.out.println("当前线程名: " + Thread.currentThread().getName() + ", 参数args: " + args);
        return "return string success!";
    }
}
           

第二步:创建一个Callable<Integer>类,返回值为Integer

import java.util.concurrent.Callable;

public class IntegerArgs implements Callable<Integer> {

    private Integer args;
    public IntegerArgs(Integer args) {
        this.args = args;
    }
	
    @Override
    public Integer call() throws Exception {
        // 执行业务逻辑
        System.out.println("当前线程名: " + Thread.currentThread().getName() + ", 参数args: " + args);
        return 666;
    }
}
           

第三步:创建一个Callable的测试类

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class CallableDemo {
	
    public static void main(String[] args) {
        // 创建一个单例线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 0L,
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(1));
		
        Future<String> fs = executor.submit(new StringArgs("String"));
        Future<Integer> fi = executor.submit(new IntegerArgs(999));
		
        try {
            System.out.println("==>String返回值为: " + fs.get());
            System.out.println("==>Integer返回值为: " + fi.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
		
        System.out.println("==>关闭线程池");
        executor.shutdown(); // 关闭线程池
    }
}
           

执行效果图:

Java多线程-Callable和Future

说明:先创建一个单例线程池,再创建两个线程任务,并添加到线程池中,通过submit的方式进行异步计算结果,再通过get的方式获取计算结果的返回值。

识别二维码关注个人微信公众号

Java多线程-Callable和Future

本章完结,待续,欢迎转载!

本文说明:该文章属于原创,如需转载,请标明文章转载来源!

继续阅读