分析以下代码并给出修正后的代码package demo1;import orgapachecommonsioFileUtils;import javaioFile;import javaioIOException;import javanetURL;import javautilconcurrent;public class TestCallable implements CallableBool
分析:
- 代码中创建了一个TestCallable类,实现了Callable接口。TestCallable类中包含了一个call()方法,用于执行下载操作。
- TestCallable类中还包含了一个WebDownloader内部类,用于实现下载的具体逻辑。
- 在main()方法中,创建了3个TestThread对象,并将它们提交给线程池执行。
- 然后通过调用Future对象的get()方法获取下载结果,并将结果打印出来。
- 最后关闭线程池。
修正后的代码如下:
package demo1;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
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 IOException {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
System.out.println("下载的文件名为:" + name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable testCallable1 = new TestCallable("https://hellorfimg-tx.zcool.cn/provider_image/preview260/2238522331.jpg", "31.jpg");
TestCallable testCallable2 = new TestCallable("https://hellorfimg-tx.zcool.cn/provider_image/preview260/2238522392.jpg", "92.jpg");
TestCallable testCallable3 = new TestCallable("https://hellorfimg-tx.zcool.cn/provider_image/preview260/2238522330.jpg", "30.jpg");
// 创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
// 提交执行
Future<Boolean> r1 = ser.submit(testCallable1);
Future<Boolean> r2 = ser.submit(testCallable2);
Future<Boolean> r3 = ser.submit(testCallable3);
// 获取结果
boolean rs1 = r1.get();
boolean rs2 = r2.get();
boolean rs3 = r3.get();
System.out.println(rs1);
System.out.println(rs2);
System.out.println(rs3);
// 关闭服务
ser.shutdown();
}
// 下载器
class WebDownloader {
// 下载方法
public void downloader(String url, String name) throws IOException {
FileUtils.copyURLToFile(new URL(url), new File(name));
}
}
}
修正后的代码主要修改了以下几点:
- 将TestThread改为TestCallable,并将其实现Callable接口。
- call()方法抛出IOException异常。
- main()方法中创建TestCallable对象。
- 删除了强制类型转换。
- 修改了异常处理逻辑
原文地址: http://www.cveoy.top/t/topic/iJ5i 著作权归作者所有。请勿转载和采集!