Callable接口学习

Callable是Java线程使用中提供的一个具有类型参数的泛型接口,通过实现该接口的call(),可以创建一个该返回值的实例。

调用实例需要使用ExecutorService.submit()。

下面的例子中,通过传入一个参数n,生成一个斐波拉契数列,然后将数列的和计算后返回。


package concurrency21;

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

class Fib implements Callable<Integer> {
	
	private static int count = 0;
	private final int id = count++;
	private List<Integer> list;
	
	private int fib(int n) {
		if (n < 2)
			return 1;
		return fib(n - 2) + fib(n - 1);
	}
	
	public Fib(int n) {
		list = new ArrayList<>(n);
		for(int i = 0; i < n; i++) {
			list.add(fib(i));
		}
	}
	
	@Override
	public String toString() {
		return "#" + id + " : " + list.toString();
	}

	@Override
	public Integer call() throws Exception {
		int result = 0;
		for(int i : list)
			result += i;
		return result;
	}
}

public class E5 {

	public static void main(String[] args) {
		ExecutorService eService = Executors.newCachedThreadPool();
		List<Future<Integer>> results = new ArrayList<>();
		for(int i = 0; i < 5; i++) {
			results.add(eService.submit(new Fib(i+8)));
		}
		
		for(Future<Integer> fi : results) {
			try {
				if(fi.isDone())
					System.out.println(fi.get());
			} catch (InterruptedException | ExecutionException e) {
				e.printStackTrace();
			}finally {
				eService.shutdown();
			}
		}
	}

}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值