利用Callable和Future

利用Callable和Future

public class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        for (int i = 0; i < 100; i++) {
            System.out.println("跟女孩表白" + i);
        }

        // 返回值就是表示线程执行完毕之后的结果
        return "答应";
    }
}


public class Demo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyCallable mc = new MyCallable();

        // Thread t1 = new Thread(mc);

        // 可以获取线程执行完毕之后的结果,也可以作为参数传递给Thread对象
        FutureTask<String> ft = new FutureTask<>(mc);

        // 创建线程对象
        Thread t1 = new Thread(ft);

        // 开启线程
        t1.start();

        // 获取线程执行完毕后返回的结果
        String s = ft.get();
        System.out.println(s);

    }
}