1. 程式人生 > 其它 >docker中安裝python3.8

docker中安裝python3.8

  1. 實現Callable介面,需要返回值型別
  2. 重寫call方法,需要丟擲異常
  3. 建立目標物件
  4. 建立執行服務:ExecutorService ser = Executors.newFixedThreadPool(1);
  5. 提交執行:Future result1 = ser.submit(t1);
  6. 獲取結果: boolean r1 = result1.get()
  7. 關閉服務: ser.shutdownNow();
package com.wang.multiThread.demo02;

import com.wang.multiThread.demo01.TestThread2;
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.可以丟擲異常
 */
public class TestCallable implements Callable {
    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 t1 = new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg12.360buyimg.com%2Fn2%2Fjfs%2Ft16657%2F184%2F2048108479%2F409928%2Fa7f806cf%2F5ae2ce54Ncdcf8bcd.jpg&refer=http%3A%2F%2Fimg12.360buyimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1646466401&t=0bcc5a77aa3cefd8335e4395ba59c753", "1.jpg");
        TestCallable t2 = new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg12.360buyimg.com%2Fn2%2Fjfs%2Ft16657%2F184%2F2048108479%2F409928%2Fa7f806cf%2F5ae2ce54Ncdcf8bcd.jpg&refer=http%3A%2F%2Fimg12.360buyimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1646466401&t=0bcc5a77aa3cefd8335e4395ba59c753", "2.jpg");
        TestCallable t3 = new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg12.360buyimg.com%2Fn2%2Fjfs%2Ft16657%2F184%2F2048108479%2F409928%2Fa7f806cf%2F5ae2ce54Ncdcf8bcd.jpg&refer=http%3A%2F%2Fimg12.360buyimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1646466401&t=0bcc5a77aa3cefd8335e4395ba59c753", "3.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異常,downloader方法出現問題");
        }
    }
}