Callable接口说明
简单示例
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Demo01 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Callable<Integer> callable = new Demo01Callable();
FutureTask<Integer> task = new FutureTask(callable);
Thread t = new Thread(task);
t.setName("测试callable线程");
t.start();
System.out.println("线程返回的值为: " + task.get());
}
}
class Demo01Callable implements Callable<Integer>{
@Override
public Integer call() throws Exception{
System.out.println(Thread.currentThread().getName()+"调用了call方法");
int val = (int)(Math.random()*10);
System.out.println("准备返回的值是: " + val);
return val;
}
}