码迷,mamicode.com
首页 > 编程语言 > 详细

java多线程 -- 创建线程的第三者方式 实现Callable接口

时间:2017-03-31 01:03:10      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:class   类设计   package   company   java   stack   com   span   code   

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

 

java多线程 -- 创建线程的第三者方式 实现Callable接口

标签:class   类设计   package   company   java   stack   com   span   code   

原文地址:http://www.cnblogs.com/androidsuperman/p/6648998.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!