Java中的多线程学习笔记002:Callable接口实现多线程

it2023-10-29  105

https://space.bilibili.com/95256449/channel/detail?cid=146244

Java中的多线程002

1、使用Callable接口实现多线程

package com.stark.study001; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.concurrent.*; /** * 线程创建方式三:实现Callable接口 * Callable的好处 * 1、可以定义返回值 * 2、可以抛出异常 **/ //线程创建方式三:实现Callable接口 public class TestCallable implements Callable<Boolean> { private String url;//网络地址 private String name;//保存的文件名 public TestCallable(String url, String name) { this.url = url; this.name = name; } //重写run方法 @Override public Boolean call() { // super.run(); 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://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png", "picture001.jpg"); TestCallable t2 = new TestCallable("https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/topnav/baiduyun@2x-e0be79e69e.png", "picture002.jpg"); TestCallable t3 = new TestCallable("https://dss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/topnav/tupian@2x-482fc011fc.png", "picture003.jpg"); //创建执行服务 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异常,WebDownloader.downloader()方法异常。"); } } }
最新回复(0)