Runnbale封装一个异步运行的任务,可以把它想象成一个没有任何参数和返回值的异步方法。Callable和Runnable相似,但是它有返回值。Callable接口是参数化的类型,只有一个方法call

public interface Callable<V> {

V call() throws Exception;

}

类型参数就是返回值的类型,例如:Callable<String>表示最终返回一个String的异步操作(计算)

Runnbale封装一个异步运行的任务,可以把它想象成一个没有任何参数和返回值的异步方法。Callable和Runnable相似,但是它有返回值。Callable接口是参数化的类型,只有一个方法call()

public interface Callable<V> {

V call() throws Exception;

}

类型参数就是返回值的类型,例如:Callable<String>表示最终返回一个String的异步操作(计算)

    //求素数
class PrimeCallable implements Callable<int[]> {
private int max; public PrimeCallable(int max) {
this.max = max;
} @Override
public int[] call() throws Exception {
List<Integer> result = new ArrayList<Integer>();
for(int i = ; i <= max; i++) {
System.out.println("System is checking data " + i);
if(isPrime(i)) {
result.add(i);
}
} Integer[] iters = result.toArray(new Integer[]{});
int[] array = new int[iters.length];
int i = ;
for(Integer iter : iters) {
array[i++] = iter;
}
return array;
} private boolean isPrime(int data) {
try {
Thread.sleep();
} catch (InterruptedException e) {
e.printStackTrace();
}
for(int i = ; i < ((int)Math.sqrt(data)+); i++) {
if(data % i == )
return false;
}
return true;
}
}
    Callable<int[]> primeCallable = new PrimeCallable();
FutureTask<int[]> ftask = new FutureTask<int[]>(primeCallable); Thread t = new Thread(ftask);
t.start(); int[] result = null;
System.out.println("Waiting for result.....");
try {
result = ftask.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} for(int i = ; result != null && i < result.length; i++) {
if(i != && i % == ) {
System.out.println();
}
System.out.print(String.format("%1$-5s", result[i]));
}
执行结果:
Waiting for result.....
System is checking data
System is checking data
System is checking data
System is checking data
System is checking data
System is checking data
..................................
System is checking data
System is checking data
05-15 04:31