java
package study;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class day03_runnable和callable {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Task1 task1 = new Task1();
new Thread(task1).start();
Task2 task2 = new Task2(10);
FutureTask<Long> futureTask = new FutureTask<Long>(task2);
new Thread(futureTask).start(); // FutureTask实现了Runnable, 所以可以传入Thread的构造函数
Long result = futureTask.get(); // 死等计算完成结果
System.out.println(result);
}
}
class Task1 implements Runnable {
@Override
public void run() {
System.out.println("Runnable");
}
}
class Task2 implements Callable<Long> {
private long num;
public Task2(int num) {
this.num = num;
}
@Override
public Long call() throws Exception {
return this.num + 10;
}
}