1、具体实现
- 创建 FutureTask 辅助类 MyCallable 实现 Callable 接口。
- 创建 MyCallable 对象:MyCallable myCallable = new MyCallable()。
- 创建 线程辅助类 FutureTask 对象:FutureTask futureTask = new FutureTask(myCallable)。
- 创建线程对象:Thread thread1 = new Thread(futureTask, “线程一”)。
- 调用线程对象的 start() 方法。
public class CallableDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable myCallable = new MyCallable();
FutureTask<Integer> futureTask = new FutureTask(myCallable);
FutureTask<Integer> futureTask2 = new FutureTask(myCallable);
Thread thread1 = new Thread(futureTask, "线程一");
Thread thread2 = new Thread(futureTask2, "线程二");
thread1.start();
thread2.start();
Integer integer1 = futureTask.get();
Integer integer2 = futureTask2.get();
System.out.println("最后剩余票数为:" + integer1 + "," + integer2);
}
static class MyCallable implements Callable<Integer> {
// 100 张票
private static int ticket = 100;
@Override
public Integer call() throws Exception {
while (ticket > 1) {
ticket--;
System.out.println(Thread.currentThread() + "卖掉了1张票,剩余票数为:" + ticket);
Thread.sleep(200L);
}
return ticket;
}
}
}
线程实现 | 特点 |
---|
继承 Thread | 单继承,无返回值 |
实现 Runnable | 可以多实现,无返回值 |
实现 Callable | 可以多实现,有返回值 |