java多线程中的callable接口实现

关于Java的多线程callable接口实现,相对比runnable接口而言了解即可,因此不多废话直接看例子:

package com.lipu.demo02;

import com.lipu.demo01.Testhread02;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

//多线程创建方式三:实现callable接口
//
public class TestCallable implements Callable<Boolean> {
    private  String  url;
    private  String  name;

    public TestCallable(String url,String name){ //构造函数初始化使用
        this.name=name;
        this.url=url;
    }
    //重写call方法
    @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://blog.kuangstudy.com/usr/uploads/2019/10/3278965235.png","011.png");//url为图片地址,name为保存图片的名称
        TestCallable t2=new TestCallable("https://blog.kuangstudy.com/usr/uploads/2019/10/3278965235.png","022.png");
        TestCallable t3=new TestCallable("https://blog.kuangstudy.com/usr/uploads/2019/10/3278965235.png","033.png");

        //创建执行服务
        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方法出现问题");
        }
    }
}
posted @ 2020-01-14 16:28  lipu1993  阅读(634)  评论(0编辑  收藏  举报