创建线程的方式有三种

1.继承Thread类

2.实现Runnable接口

3.实现Callable接口

第三种方式,可以通过FutureTask包装类调用get()方法获取到线程的返回值

也可以通过ExecutorService创建的线程池调用submit()方法返回一个Future对象来获取线程的返回值

public class FutureTest {

    public static void main(String[] args) {
        // futureTask();
        FutureTask<?> futureTask = new FutureTask<>(new CallableThreadTest());
        for (int i = 0; i < 20; i++) {
            System.out.println(Thread.currentThread().getName() + " 的循环变量i的值" + i);
            if (i == 10) {
                new Thread(futureTask, "有返回值的线程").start();
            }
        }
        try {
            System.out.println("子线程的返回值:" + futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private static class CallableThreadTest implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            int i = 0;
            for (; i < 20; i++) {
                System.out.println(Thread.currentThread().getName() + "--" + i);
            }
            return i;
        }
    }

    private static void futureTask() {
        FutureTask<Integer> task = new FutureTask<>(() -> {
            System.out.println(Thread.currentThread().getName() + "   " + "开始执行任务!");
            return 0;
        });
        new Thread(task, "新线程").start();
        try {
            System.out.print(task.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}

  

posted on 2019-09-12 22:54  MC伍  阅读(228)  评论(0编辑  收藏  举报