多线程---实现Callable接口

实现Callable接口

 

 

案例:

package com.mokuiran.thread;

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 CallableDemo implements Callable<Boolean> {
   private String url;//网络图片的地址
   private String name;//保存的文件名

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

   @Override
   public Boolean call() {
       WebDownLoader2 webDownLoader2 = new WebDownLoader2();
       webDownLoader2.downloader(url,name);
       System.out.println("下载的文件名:"+name);
       return true;
  }

   public static void main(String[] args) throws ExecutionException, InterruptedException {
       CallableDemo demo1 = new CallableDemo("https://img2022.cnblogs.com/blog/2941481/202207/2941481-20220730105748137-1136505936.png","代码.png");
       CallableDemo demo2 = new CallableDemo("https://img2022.cnblogs.com/blog/2941481/202207/2941481-20220730105748137-1136505936.png","代码2.png");

       //创建执行服务:
       ExecutorService ser = Executors.newFixedThreadPool(2);

       //提交执行
       Future<Boolean> r1 = ser.submit(demo1);
       Future<Boolean> r2 = ser.submit(demo2);

       //获取结果
       boolean rs1 = r1.get();
       boolean rs2 = r2.get();

       //关闭服务
       ser.shutdownNow();

  }
}
class WebDownLoader2{
   //下载方法
   public void downloader(String url,String name){
       try {
           FileUtils.copyURLToFile(new URL(url),new File(name));
      } catch (IOException e) {
           e.printStackTrace();
           System.out.println("异常,downloader()方法出现问题");
      }
  }
}
 
posted @   默夔然  阅读(100)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示