一样是启动线程 但是Callable要通过FutureTask包装后 用FutureTask对象作为构造参数创建线程
Callable中的call()方法代替了Runnable中的run()方法,可以有返回值,可以带异常
返回值是通过FutureTask的get()方法拿到的
- import java.io.IOException;
- import java.util.Random;
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.FutureTask;
- public class Test {
- public static void main(String[] args) throws IOException, InterruptedException, ExecutionException
- {
- final int[] arr = new int[10];
- Callable<int[]> cl = new Callable<int[]>(){
- public int[] call()
- {
- for(int i = 0;i<10;i++)
- {
- arr[i] = new Random().nextInt(100);
- System.out.println("添加第"+i+"個元素!");
- }
- return arr;
- }
- };
- FutureTask<int[]> task = new FutureTask<int[]>(cl);
- new Thread(task){}.start();
- for(int i : task.get())
- System.out.print(i+" ");
- }
- }
复制代码 |