线程的创建 - 实现Callable接口

HeJin小于 1 分钟Java多线程详解

  1. 实现Callable接口,需要返回值类型
  2. 重写Call方法,需要抛出异常
  3. 创建目标对象
  4. 创建执行服务
  5. 提交执行
  6. 获取结果
  7. 关闭服务
public class TestCallable implements Callable<Boolean> {

    private String url;
    private String name;

    public TestCallable(String url, String name){
        this.url = url;
        this.name = name;
    }

    /**
     * 下载图片线程的执行体
     */
    @Override
    public Boolean call() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url, name);
        System.out.println("下载了文件名为:" + name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        TestCallable thread1 = new TestCallable("https://img-blog.csdnimg.cn/20210305120636825.png","1.png");
        TestCallable thread2 = new TestCallable("https://img-blog.csdnimg.cn/20210305121018539.png","2.png");
        TestCallable thread3= new TestCallable("https://img-blog.csdnimg.cn/20210305121930543.png","3.png");

        // 创建执行服务
        ExecutorService service = Executors.newFixedThreadPool(3);
        // 提交执行
        Future<Boolean> r1 = service.submit(thread1);
        Future<Boolean> r2 = service.submit(thread2);
        Future<Boolean> r3 = service.submit(thread3);
        // 获取结果
        Boolean rs1 = r1.get();
        Boolean rs2 = r2.get();
        Boolean rs3 = r3.get();
        System.out.println(rs1);
        System.out.println(rs2);
        System.out.println(rs3);
        // 关闭服务
        service.shutdown();

    }

}

/**
 * 下载器
 */
class WebDownloader{
    public void downloader(String url, String name){
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Io异常,downloader方法出现问题.");
        }
    }
}

通过实现Callable接口创建线程的好处

  • 可以定义返回值
  • 可以抛出异常