创建线程的第三种方式

Posted by 小兵兵 on Friday, December 6, 2019

目录

使用Callable接口

Thread可以通过其构造函数传入Runnable接口创建线程,那么这和Callable接口有什么关系呢

1575624654859

FutureTask类实现了Runnable接口,那么我们是不是可以通过Thread其构造函数传入FutureTask

1575624866258

FutureTask的构造函数传入了Callable接口

1575624987612

通过以上关系图,可以使用Callable接口来创建线程,注意到call方法有返回值、抛出异常

package com.zbiti.juc;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> futureTask = new FutureTask(new MyThread());
        new Thread(futureTask,"A").start();
        Integer count = futureTask.get();
        System.out.println(count);
    }

}

class MyThread implements Callable{

    @Override
    public Integer call() throws Exception {
        System.out.println("*********come in call method");
        return 1024;
    }
}