Runnable
->RunnableFuture
->FutureTask
(实现类)FutureTask
有构造方法:public FutureTask(Callable<V> callable)
- 示例
public class CallableDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask futureTask = new FutureTask(new MyThread());
new Thread(futureTask,"A").start();
System.out.println(futureTask.get());
}
}
class MyThread implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("******************");
return 1024;
}
}
get()
方法的使用public class CallableDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask futureTask = new FutureTask(new MyThread());
new Thread(futureTask,"A").start();
System.out.println(Thread.currentThread().getName()+"线程完成");
System.out.println(futureTask.get());
}
}
class MyThread implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("******************");
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 1024;
}
}
输出结果:******************
main main线程完成
1024
get
方法要在后面调用,因为一旦调用,程序会一直等待到该线程完成- 多个分线程
public class CallableDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask futureTask = new FutureTask(new MyThread());
new Thread(futureTask,"A").start();
new Thread(futureTask,"B").start();
System.out.println(Thread.currentThread().getName()+"线程完成");
System.out.println(futureTask.get());
}
}
class MyThread implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName());
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 1024;
}
}
结果:A
main线程完成
1024