zoukankan      html  css  js  c++  java
  • Java多线程之Callable接口的实现

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.FutureTask;
     
    /*
     * 一、创建执行线程的方式三:实现 Callable 接口。 相较于实现 Runnable 接口的方式,方法可以有返回值,并且可以抛出异常。
     *
     * 二、执行 Callable 方式,需要 FutureTask 实现类的支持,用于接收运算结果。  FutureTask 是  Future 接口的实现类
     */
    public class TestCallable {
     
        public static void main(String[] args) {
            ThreadDemo td = new ThreadDemo();
     
            //1.执行 Callable 方式,需要 FutureTask 实现类的支持,用于接收运算结果。
            FutureTask<Integer> result = new FutureTask<>(td);
     
            new Thread(result).start();
     
            //2.接收线程运算后的结果
            try {
                Integer sum = result.get();  //FutureTask 可用于 闭锁 类似于CountDownLatch的作用,在所有的线程没有执行完成之后这里是不会执行的
                System.out.println(sum);
                System.out.println("------------------------------------");
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
     
    }
     
    class ThreadDemo implements Callable<Integer> {
     
        @Override
        public Integer call() throws Exception {
            int sum = 0;
     
            for (int i = 0; i <= 100000; i++) {
                sum += i;
            }
     
            return sum;
        }
     
    }

     综上例子可以看到: Callable 和 Future接口的区别

    1.   (1)Callable规定的方法是call(),而Runnable规定的方法是run(). 
    2.   (2)Callable的任务执行后可返回值,而Runnable的任务是不能返回值的。  
    3.   (3)call()方法可抛出异常,而run()方法是不能抛出异常的。 
    4.   (4)运行Callable任务可拿到一个Future对象, Future表示异步计算的结果。 
    5.   它提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。 
    6.   通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果。 
    7. Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其它线程执行的任务。 

     

  • 相关阅读:
    关于返回上一页功能
    Mybatis Update statement Date null
    SQLite reset password
    Bootstrap Validator使用特性,动态(Dynamic)添加的input的验证问题
    Eclipse使用Maven2的一次环境清理记录
    Server Tomcat v7.0 Server at localhost failed to start
    PowerShell一例
    Server Tomcat v7.0 Server at libra failed to start
    商标注册英语
    A glance for agile method
  • 原文地址:https://www.cnblogs.com/edda/p/12688654.html
Copyright © 2011-2022 走看看