多线程创建方式三 - 实现Callable接口

简介: 多线程创建方式三 - 实现Callable接口

Java 5.0 在java.util.concurrent 提供了一个新的创建执行线程的方式:Callable 接口。


Callable 接口类似于Runnable,两者都是为那些其实例可能被另一个线程执行的类设计的。但是Runnable 不会返回结果,并且无法抛出经过检查的异常。


Callable接口示例如下:

public class TestCallable {
    public static void main(String[] args){
        CallableDemo callableDemo = new CallableDemo();
        //执行Callable需要有FutureTask支持,用于接收运算结果
        FutureTask<Integer> futureTask = new FutureTask<>(callableDemo);
        new Thread(futureTask).start();
        try {
            //接收线程运算后结果
            Integer sum = futureTask.get();
            System.out.println(sum);
            //futureTask.get();执行完才能打印横线,说明
            System.out.println("--------------------------------------");
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
class CallableDemo implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        int sum=0;
        for (int i=0;i<=100;i++){
            System.out.println(i);
            sum+=i;
        }
        return sum;
    }
}

jdk1.8下可以使用lambda表达式,修改如下:

FutureTask<Integer> futureTask = new FutureTask<>(()->{
   int sum=0;
        for (int i=0;i<=100;i++){
            System.out.println(i);
            sum+=i;
        }
        return sum;
});
new Thread(futureTask).start();

Callable 需要依赖FutureTask ,FutureTask 也可以用作闭锁。

如下图所示,只有获取到结果后才会打印横线:


FutureTask拥有方法如下:

其实现了RunnableFuture接口:

public class FutureTask<V> implements RunnableFuture<V> {
//...
}

其中RunnableFuture接口又继承自Runnable和Future接口:

 // 一个Future 就是一个Runnable,run方法的成功执行会使得Future结束并访问结果
public interface RunnableFuture<V> extends Runnable, Future<V> {
     //将此未来设置为其计算结果,除非已取消
    void run();
}

Future是什么,有什么用?

查看其javadoc如下:

/**
 * A {@code Future} represents the result of an asynchronous
 * computation.  Methods are provided to check if the computation is
 * complete, to wait for its completion, and to retrieve the result of
 * the computation.  The result can only be retrieved using method
 * {@code get} when the computation has completed, blocking if
 * necessary until it is ready.  Cancellation is performed by the
 * {@code cancel} method.  Additional methods are provided to
 * determine if the task completed normally or was cancelled. Once a
 * computation has completed, the computation cannot be cancelled.
 * If you would like to use a {@code Future} for the sake
 * of cancellability but not provide a usable result, you can
 * declare types of the form {@code Future<?>} and
 * return {@code null} as a result of the underlying task.
目录
相关文章
|
2月前
|
存储 Java
高并发编程之多线程锁和Callable&Future 接口
高并发编程之多线程锁和Callable&Future 接口
28 1
|
4月前
|
Java
JAVA JUC Callable 接口
【1月更文挑战第5天】JAVA JUC Callable 接口
|
22天前
|
Java
Java中的多线程实现:使用Thread类与Runnable接口
【4月更文挑战第8天】本文将详细介绍Java中实现多线程的两种方法:使用Thread类和实现Runnable接口。我们将通过实例代码展示如何创建和管理线程,以及如何处理线程同步问题。最后,我们将比较这两种方法的优缺点,以帮助读者在实际开发中选择合适的多线程实现方式。
24 4
|
2月前
|
Java
Java并发编程:理解并使用Future和Callable接口
【2月更文挑战第25天】 在Java中,多线程编程是一个重要的概念,它允许我们同时执行多个任务。然而,有时候我们需要等待一个或多个线程完成,然后才能继续执行其他任务。这就需要使用到Future和Callable接口。本文将深入探讨这两个接口的用法,以及它们如何帮助我们更好地管理多线程。
|
2月前
|
Java
创建线程的三种方式:继承Thread、Runnable 接口、Callable 接口
创建线程的三种方式:继承Thread、Runnable 接口、Callable 接口
|
3月前
|
Java 程序员
【JavaEE初阶】 Callable 接口
【JavaEE初阶】 Callable 接口
|
5月前
|
安全 Java C++
多线程之Callable接口、ReentrantLock、信号量 Semaphore以及CountDownLatch
多线程之Callable接口、ReentrantLock、信号量 Semaphore以及CountDownLatch
|
1天前
|
监控 安全 Java
【多线程学习】深入探究阻塞队列与生产者消费者模型和线程池常见面试题
【多线程学习】深入探究阻塞队列与生产者消费者模型和线程池常见面试题
|
1天前
|
缓存 安全 Java
多线程--深入探究多线程的重点,难点以及常考点线程安全问题
多线程--深入探究多线程的重点,难点以及常考点线程安全问题
|
1天前
|
数据采集 安全 Java
Python的多线程,守护线程,线程安全
Python的多线程,守护线程,线程安全

热门文章

最新文章