多线程实现callable接口的方式与不同

实现callable接口

//callable是有返回值的,与Runnable接口不同
package com.lening.thread;

import org.apache.commons.io.FileUtils;

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

/**
 * @Author WangEn
 * @CreateTime: 2021-04-10-11-44
 * @Emile: wen_5988@163.com
 */
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() throws Exception {
        new UpDownLoad1().upDownLoad(url,name);
        System.out.println("下载的图片名字是"+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable("https://img1.baidu.com/it/u=1485012388,2380514454&fm=26&fmt=auto&gp=0.jpg","地球.jpg");
        TestCallable t2 = new TestCallable("https://img2.baidu.com/it/u=3355464299,584008140&fm=26&fmt=auto&gp=0.jpg","A梦.jpg");
        TestCallable t3 = new TestCallable("https://img1.baidu.com/it/u=2496571732,442429806&fm=26&fmt=auto&gp=0.jpg","水.jpg");
        // 创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(1);
        // 执行提交
        Future<Boolean> s1 = ser.submit(t1);
        Future<Boolean> s2 = ser.submit(t2);
        Future<Boolean> s3 = ser.submit(t3);
        // 获取结果
        Boolean result1 = s1.get();
        Boolean result2 = s2.get();
        Boolean result3 = s3.get();
        // 关闭服务
        ser.shutdownNow();

        /**
         * 三个线程池:
         * 正在执行的线程执行完结束,线程池的线程不执行
         * ser.shutdownNow();
         * 正在执行的线程执行完结束,线程池的线程执行完结束
         * ser.shutdown();
         */
    }

}

/**
 * 下图工具类
 */
class UpDownLoad1{
    public void upDownLoad(String url,String name) throws MalformedURLException {
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("图片下载失败");
        }
    }
}

![callable接口的启动方式](

posted @ 2021-04-10 12:58  W·EN  阅读(74)  评论(0)    收藏  举报