Java實現Callable接口


實現Callable接口

  1. 實現Callable接口,需要返回值類型
  2. 重寫call方法,需要拋出異常
  3. 創建目標對象
  4. 創建執行服務:ExecutorService ser = Executors.newFixedThreadPool(1);
  5. 提交執行:Future result1 = ser.submit(t1);
  6. 獲取結果:boolean r1 = result1.get()
  7. 關閉服務:ser.shutdowmNow();
package com.xiao.demo01;

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<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 testThread1 = new TestCallable("https://img2020.cnblogs.com/blog/35695/202102/35695-20210228140227933-2125906102.jpg", "2.jpg");
        TestCallable testThread2 = new TestCallable("https://img2020.cnblogs.com/blog/35695/202102/35695-20210228140227933-2125906102.jpg", "2.jpg");
        TestCallable testThread3 = new TestCallable("https://img2020.cnblogs.com/blog/35695/202102/35695-20210228140227933-2125906102.jpg", "2.jpg");

        //創建執行服務:
        ExecutorService ser = Executors.newFixedThreadPool(3);

        //提交執行
        Future<Boolean> r1 = ser.submit(testThread1);
        Future<Boolean> r2 = ser.submit(testThread2);
        Future<Boolean> r3 = ser.submit(testThread3);

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

        System.out.println(rs1);
        System.out.println(rs2);
        System.out.println(rs3);

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


    }


    //下載方法
    public void downloader(String url, String name) {
        try {
            try {
                FileUtils.copyURLToFile(new URL(url), new File(name));
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("IO異常,downloader方法出現問題");
            }
        } finally {

        }
    }
}

實現Callable接口創建線程


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM