线程创建--实现Callable接口

步骤

  • 实现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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值