Java:Callable

阎智
2023-12-01
1、具体实现
  1. 创建 FutureTask 辅助类 MyCallable 实现 Callable 接口。
  2. 创建 MyCallable 对象:MyCallable myCallable = new MyCallable()。
  3. 创建 线程辅助类 FutureTask 对象:FutureTask futureTask = new FutureTask(myCallable)。
  4. 创建线程对象:Thread thread1 = new Thread(futureTask, “线程一”)。
  5. 调用线程对象的 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可以多实现,有返回值
 类似资料:

相关阅读

相关文章

相关问答