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
  • 相关阅读:
    XP显示桌面
    批量改名
    poj 3126 BFS
    poj 3278 BFS
    poj 1426 BFS
    准备打酱油…
    POJ 2243 BFS 和 简单的调试方法学习
    K
    EXCEL fundamentals
    poj 1011 DFS+剪枝
  • 原文地址:https://www.cnblogs.com/androidsuperman/p/6648998.html
Copyright © 2011-2022 走看看