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();
}
}
这里主要是根据数组的下标划分两个子数组。