并发编程之Callable方法的详细解析(带小案例)

本文涉及的产品
全局流量管理 GTM,标准版 1个月
云解析 DNS,旗舰版 1个月
公共DNS(含HTTPDNS解析),每月1000万次HTTP解析
简介: 并发编程之Callable方法的详细解析(带小案例)

Callable

(第三种线程实现方式)

Callable与Runnable的区别

Callable与Runnable的区别

  1. 实现方法名称不一样
  2. 有返回值
  3. 抛出了异常



class Thread1 implements Runnable{
    @Override
    public void run() {
    }
}
class Thread2 implements Callable<Integer>{
    //1.方法名称不一样  2.有返回值  3.抛出了异常
    @Override
    public Integer call() throws Exception {
        return null;
    }
}

Callable的使用

Callable线程类的运行,需要依靠FutureTask的封装,因为Thread类的构造方法只支持Runnable及其子类,于是就需要继承了Runnable的FutureTast来对Callable子类进行封装,下面是FurtureTast的继承关系源代码:

public class FutureTask<V> implements RunnableFuture<V> {

public interface RunnableFuture<V> extends Runnable, Future<V> {

public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> futureTask = new FutureTask<>(new Thread2());
        new Thread(futureTask).start();
        System.out.println(futureTask.get());
    }
}
class Thread2 implements Callable<Integer>{
    //1.方法名称不一样  2.有返回值  3.抛出了异常
    @Override
    public Integer call() throws Exception {
        System.out.println("come in");
        return 1024;
    }
}

Callable的细节

使用callable就相当于另外开了一条线程运行,调用get方法就相当于要获取这条线程的运行结果。

如果在mian线程中调用了get方法,就会阻塞起来等待这个线程的运行结果。

于是就出现如下情况:

demo1

运行结果:

代码:

public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> futureTask = new FutureTask<>(new Thread2());
        new Thread(futureTask).start();
        System.out.println("main");
        System.out.println(futureTask.get()); //后调用get方法
    }
}
class Thread2 implements Callable<Integer>{
    //1.方法名称不一样  2.有返回值  3.抛出了异常
    @Override
    public Integer call() throws Exception {
        Thread.sleep(2000);
        System.out.println("come in");
        return 1024;
    }
}
demo2

运行结果:

代码:

public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> futureTask = new FutureTask<>(new Thread2());
        new Thread(futureTask).start();
        System.out.println(futureTask.get()); //先调用get方法,会在这里等待线程返回结果
        System.out.println("main");
    }
}
class Thread2 implements Callable<Integer>{
    //1.方法名称不一样  2.有返回值  3.抛出了异常
    @Override
    public Integer call() throws Exception {
        Thread.sleep(2000);
        System.out.println("come in");
        return 1024;
    }
}

Callable的细节2

callable多次运行,只会计算一次结果

运行结果:(可以看到 只执行了一次come in的输出,即call()这个方法的代码只运行了一次)

代码:



public class CallableDemo2 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> futureTask = new FutureTask<>(new Thread3());
        Thread t1 = new Thread(futureTask);  //第一次调用 这个 futruetask任务
        t1.start();
        Thread t2 = new Thread(futureTask);  //第二次调用 这个 futruetask任务
        t2.start();
        System.out.println(futureTask.get());
        System.out.println(futureTask.get());
        System.out.println("main");
    }
}
class Thread3 implements Callable<Integer>{
    private static int num = 0;
    //1.方法名称不一样  2.有返回值  3.抛出了异常
    @Override
    public Integer call() throws Exception {
        System.out.println("come in");
        return ++num;
    }
}

原生Thread多次执行start会抛出IllegalThreadStateException非法的线程状态异常,Callable也是一样

Thread的start() 源码:

public synchronized void start() {
     /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();  //如果线程已经启动,则抛出异常
        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);
        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }


相关文章
|
15天前
|
数据采集 人工智能 安全
数据治理的实践与挑战:大型案例解析
在当今数字化时代,数据已成为企业运营和决策的核心资源。然而,随着数据量的爆炸性增长和数据来源的多样化,数据治理成为了企业面临的重要挑战之一。本文将通过几个大型案例,探讨数据治理的实践、成效以及面临的挑战。
数据治理的实践与挑战:大型案例解析
|
3天前
|
存储 算法 Java
解析HashSet的工作原理,揭示Set如何利用哈希算法和equals()方法确保元素唯一性,并通过示例代码展示了其“无重复”特性的具体应用
在Java中,Set接口以其独特的“无重复”特性脱颖而出。本文通过解析HashSet的工作原理,揭示Set如何利用哈希算法和equals()方法确保元素唯一性,并通过示例代码展示了其“无重复”特性的具体应用。
14 3
|
4天前
|
存储 JavaScript 前端开发
Vue3权限控制全攻略:路由与组件层面的用户角色与权限管理方法深度解析
Vue3权限控制全攻略:路由与组件层面的用户角色与权限管理方法深度解析
18 2
|
4天前
|
SQL 监控 数据库
SQL语句是否都需要解析及其相关技巧和方法
在数据库管理中,SQL(结构化查询语言)语句的使用无处不在,它们负责数据的查询、插入、更新和删除等操作
|
8天前
|
存储
让星星⭐月亮告诉你,HashMap的put方法源码解析及其中两种会触发扩容的场景(足够详尽,有问题欢迎指正~)
`HashMap`的`put`方法通过调用`putVal`实现,主要涉及两个场景下的扩容操作:1. 初始化时,链表数组的初始容量设为16,阈值设为12;2. 当存储的元素个数超过阈值时,链表数组的容量和阈值均翻倍。`putVal`方法处理键值对的插入,包括链表和红黑树的转换,确保高效的数据存取。
29 5
|
12天前
|
SQL 存储 数据库
SQL语句是否都需要解析及其相关技巧与方法
在数据库管理系统中,SQL(Structured Query Language)语句作为与数据库交互的桥梁,其执行过程往往涉及到一个或多个解析阶段
|
22天前
|
数据处理 Python
Python 高级技巧:深入解析读取 Excel 文件的多种方法
在数据分析中,从 Excel 文件读取数据是常见需求。本文介绍了使用 Python 的三个库:`pandas`、`openpyxl` 和 `xlrd` 来高效处理 Excel 文件的方法。`pandas` 提供了简洁的接口,而 `openpyxl` 和 `xlrd` 则针对不同版本的 Excel 文件格式提供了详细的数据读取和处理功能。此外,还介绍了如何处理复杂格式(如合并单元格)和进行性能优化(如分块读取)。通过这些技巧,可以轻松应对各种 Excel 数据处理任务。
55 16
|
11天前
|
数据格式
常用的Lambda表达式案例解析,工作中都会用到!
常用的Lambda表达式案例解析,工作中都会用到!
|
18天前
|
搜索推荐 Shell
解析排序算法:十大排序方法的工作原理与性能比较
解析排序算法:十大排序方法的工作原理与性能比较
37 9
|
19天前
|
存储 编译器 C++
【初阶数据结构】掌握二叉树遍历技巧与信息求解:深入解析四种遍历方法及树的结构与统计分析
【初阶数据结构】掌握二叉树遍历技巧与信息求解:深入解析四种遍历方法及树的结构与统计分析

推荐镜像

更多