1. 程式人生 > 實用技巧 >Java中的多執行緒學習筆記002:Callable介面實現多執行緒

Java中的多執行緒學習筆記002:Callable介面實現多執行緒

https://space.bilibili.com/95256449/channel/detail?cid=146244

Java中的多執行緒002

1、使用Callable介面實現多執行緒

package com.stark.study001;

import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/**
 * 執行緒建立方式三:實現Callable介面
 * Callable的好處
 * 1、可以定義返回值
 * 2、可以丟擲異常
 **/

//執行緒建立方式三:實現Callable介面
public class TestCallable implements Callable<Boolean> {
    private String url;//網路地址
    private String name;//儲存的檔名

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

    //重寫run方法
    @Override
    public Boolean call() {
//        super.run();
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url, name);
        System.out.println(name + "檔案已下載");
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png", "picture001.jpg");
        TestCallable t2 = new TestCallable("https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/topnav/[email protected]", "picture002.jpg");
        TestCallable t3 = new TestCallable("https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/topnav/[email protected]", "picture003.jpg");

        //建立執行服務
        ExecutorService ser = Executors.newFixedThreadPool(3);
        //提交執行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);

        //獲取結果
        boolean rs1 = r1.get();
        boolean rs2 = r2.get();
        boolean rs3 = r3.get();

        //關閉服務
        ser.shutdownNow();
    }
}

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異常,WebDownloader.downloader()方法異常。");
        }
    }
}