| package demo2; |
| |
| 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() { |
| WebDownloader webDownloader = new WebDownloader(); |
| webDownloader.Download(url,name); |
| System.out.println("下载类文件名为:"+name); |
| return true; |
| } |
| |
| public static void main(String[] args) throws ExecutionException, InterruptedException { |
| |
| TestCallable t1 = new TestCallable("https://www.apple.com.cn/v/imac-24/e/images/overview/colors_lifestyle_fallback__fat816a51hua_large.jpg","p1.jpg"); |
| TestCallable t2 = new TestCallable("https://img1.baidu.com/it/u=3855106272,1253404534&fm=253&fmt=auto&app=138&f=JPEG?w=678&h=500","p2.jpg"); |
| TestCallable t3 = new TestCallable("https://img1.baidu.com/it/u=3252704542,3882037568&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500","p3.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(); |
| System.out.println(rs1); |
| System.out.println(rs2); |
| System.out.println(rs3); |
| |
| ser.shutdownNow(); |
| |
| |
| } |
| } |
| |
| |
| |
| class WebDownloader{ |
| public void Download(String url,String name){ |
| try { |
| FileUtils.copyURLToFile(new URL(url),new File(name)); |
| } catch (IOException e) { |
| e.printStackTrace(); |
| System.out.println("IO异常"); |
| } |
| } |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义