0
点赞
收藏
分享

微信扫一扫

线程创建--实现Callable接口

zidea 2022-03-30 阅读 48

步骤

  • 实现Callable接口,需要返回值类型
  • 重写call方法,需要抛出异常
  • 创建目标对象
  • 创建执行服务
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    这是一个线程池,3,代表这个线程池里面可以有三个线程
  • 提交执行
    Future t1 = executorService.submit(testThread01);
  • 获取结果
    Boolean Boolean1 = t1.get();
  • 关闭服务
    executorService.shutdown();
package com.yf.demo02;

import com.yf.demo1.TestThread01;
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 name;//网络图片地址
    private String url;//保存的文件名

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


    @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 testThread01 = new TestCallable("https://maven.apache.org/images/maven-logo-black-on-white.png","1.jpg");
        TestCallable testThread02 = new TestCallable("https://maven.apache.org/images/apache-maven-project.png","2.jpg");
        TestCallable testThread03 = new TestCallable("https://maven.apache.org/images/logos/maven-feather.png","3.jpg");
        //创建执行服务:线程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        //提交执行
        Future<Boolean> t1 = executorService.submit(testThread01);
        Future<Boolean> t2 = executorService.submit(testThread02);
        Future<Boolean> t3 = executorService.submit(testThread03);
        //获取结果
        Boolean Boolean1 = t1.get();
        Boolean Boolean2 = t2.get();
        Boolean Boolean3 = t3.get();
        //关闭服务
        executorService.shutdown();
    }
}

class WebDownLoader{
    public void downLoader(String url,String name){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
举报

相关推荐

0 条评论