Java线程之Callable接口实现线程

Callable接口实现线程

Callable接口性质概述

Callable接口是一种具有类型参数的泛型,它的类型参数是从call()方法中返回的值,而且必须使用ExecutorService.submit()方法调用它。下面是该接口的源码
	public interface Callable<V> {
   	    /**
    	     * Computes a result, or throws an exception if unable to do so.
    	     *
     	     * @return computed result
    	     * @throws Exception if unable to compute a result
     	    */
    	    V call() throws Exception;
	}
从注释中我们可以看到,call()方法不仅可以返回值,而且还能抛出异常。

Callable接口的简单用法实例

下面是我根据Callable接口的性质,写的简单地应用实例。
首先,定义一个类它实现了Callable接口,
	public class CallableTest implements Callable<String>{

		private String name;
	
		public CallableTest(String name){
			this.name = name;
		}
		@Override
		public String call() throws Exception {
		
			return name;
		}
	}
注意,Callable中泛型的类型要与call()方法返回的类型一致。然后,我们再定义一个类测试结果
	public class CallableMain {

		public static void main(String[] args){
		
			ExecutorService exec = Executors.newCachedThreadPool();
			Future<String> fu = exec.submit(new CallableTest("test"));
		
			try {
				System.out.println("Callable return is " + fu.get());
			} catch (InterruptedException | ExecutionException e) {
				e.printStackTrace();
			}
		}
	}
Callable接口的返回的是Future接口的实例化的类,所以需要这个接口来接收。调用Future接口中的get()方法来去的返回值。

基于Callable接口实现查找一组序列中最大值的程序

	public class FindMax implements Callable<Integer>{

		private int[] array;
		private int start;
		private int end;
	
		public FindMax(int[] A,int start,int end){
			this.array = A;
			this.start = start;
			this.end = end;
		}
		
		@Override
		public Integer call() throws Exception {

			int max = Integer.MIN_VALUE;
		
			for(int i = start; i < end; i++){
				if(max < array[i]){
					max = array[i];
				}
			}
			return max;
		}
	}

public class Main {

	public static void main(String[] args){
		
		int[] array = {8,7,2,3,4,5,1,5,3,9,0,1,8};
		int length = array.length;
		
		ExecutorService exec = Executors.newCachedThreadPool();
		
		Future<Integer> fu1 = exec.submit(new FindMax(array,0,length/2));
		Future<Integer> fu2 = exec.submit(new FindMax(array,length/2+1,length));
		
		try {
			if(fu1.get() > fu2.get()){
				System.out.println("The max is " + fu1.get());
			}else{
				System.out.println("The max is " + fu2.get());
			}
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
		exec.shutdown();
	}
}

这里主要是根据数组的下标划分两个子数组。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值