java使用Callable创建又返回值的线程

并发编程使我们可以将程序分为很多个分离的,相互之间独立的任务,通过使用多线程的机制,将每个任务都会有一个执行线程来单独的驱动,一个线程是 进程中一个单一顺序控制流,一个进程可以拥有多个线程,也就相当于有多个单独的顺序控制流,所以你的进程当中每个线程看起来都是有单独的cpu一样,底层实现就是切分cpu的时间片。
实现线程的方法
1 直接继承Thread类 然后重写run方法 局限性特别大 因为 任何一个类都只能继承一个父类 继承了线程 不可以继承其他类
2 继承Runnable 接口 重写run方法 r然后将 这个类的实例 当作参数传给Thread的构造器 创建线程这种方法 优于上面的方法 接口可以继承任意数量
但是上述两种方式 都有一个缺点那就是线程执行后是没有返回值的
为了实现在线程执行后 返回结果集 引进一种新的方式 实现Callable接口
实现Callable接口 实现了 会返回结果 可以在从线程执行的时候使用funture 来接收返回值!
下面是实现线程的代码
package test.link.thread;


import java.util.concurrent.Callable;

/**
 * Callable<T> T的类型就是你要返回对象的类型!
 * @author Administrator
 *
 */
 class TaskWithResult implements Callable<String> {
	private static int num;
	private int id;
	public TaskWithResult() {
		id = num++;
		System.out.println("线程#"+id+"开始初始化");
	}
	@Override
	public String call() throws Exception {
		for(int i=0;i<3;i++){
			System.out.println("call ing...");
		}
		System.out.println("线程#"+id+"即将结束");
		return "Results of Task: "+id;
	}

}

 下面是如何接收线程返回值的代码

package test.link.thread;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Demo {
    public static void main(String[] args) {
        ExecutorService exc = Executors.newCachedThreadPool();
        ArrayList<Future<String>> res = new ArrayList<Future<String>>();
        res.add(exc.submit(new TaskWithResult()));
        for(Future<String > r: res){
            try {
                System.out.println(r.get());
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally {
                exc.shutdown();
            }
        }
        
    }
}

 

 

转载于:https://www.cnblogs.com/ChenD/p/Callable.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值