zoukankan      html  css  js  c++  java
  • java多线程 -- 创建线程的第三者方式 实现Callable接口

    Java 5.0 在 java.util.concurrent 提供了一个新的创建执行线程的方式:Callable 接口
    Callable 接口类似于 Runnable,两者都是为那些其实例可能被另一个线程执行的类设计的。但是 Runnable 不会返回结果,并且无法抛出经过检查的异常
    Callable 需要依赖FutureTask ,FutureTask 也可以用作闭锁。

    例子:

    package com.company;
    
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.FutureTask;
    
    /**
     * Created by MSI1 on 2017/3/30.
     */
    public class TestCallableDemo {
    
        public static void main(String[] args) {
    
            try {
                DemoThread demoThread = new DemoThread();
                FutureTask<Integer> integerFutureTask = new FutureTask<>(demoThread);
                new Thread(integerFutureTask).start();
                Integer result = integerFutureTask.get();
                System.out.println("result = " + result);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
    
        }
    }
    
    class DemoThread implements Callable<Integer> {
    
        @Override
        public Integer call() throws Exception {
            int sum = 0;
            for (int i = 0; i <= 100; i++) {
                sum = sum + i;
            }
            return sum;
        }
    }

    結果:

    result = 5050
  • 相关阅读:
    codevs 1450 xth 的旅行
    Loj #6287 诗歌
    Codeforces 323C Two permutations
    Spoj MKTHNUM
    [TJOI2015]弦论
    Spoj SUBLEX
    bzoj 4338: BJOI2015 糖果
    bzoj 3462: DZY Loves Math II
    bzoj 2843: 极地旅行社
    清北学堂模拟赛d4t5 b
  • 原文地址:https://www.cnblogs.com/androidsuperman/p/6648998.html
Copyright © 2011-2022 走看看