Thread之Callable介面
阿新 • • 發佈:2021-02-11
Callable介面說明
簡單示例
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* @author layman
* @date 2021/2/10
*/
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;
}
}