2、实现runnable接口
实现runnable接口
import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.net.URL; public class TestThread2 implements Runnable { private String url;//图片地址 private String name;//保存文件名 //构造器 public TestThread2(String url,String name) { this.url = url; this.name = name; } //重写run方法 @Override public void run(){ WebDownload webdownload = new WebDownload(); webdownload.download(url,name); System.out.println("下载的文件名为:"+name); } public static void main(String[] args) { TestThread2 thread1 = new TestThread2("https://img-home.csdnimg.cn/images/20220707025239.jpg","123.jpg"); TestThread2 thread2 = new TestThread2("https://img-home.csdnimg.cn/images/20220707025239.jpg","124.jpg"); TestThread2 thread3 = new TestThread2("https://img-home.csdnimg.cn/images/20220707025239.jpg","125.jpg"); //创建线程对象,使用线程开启start,代理 new Thread(thread1).start(); new Thread(thread2).start(); new Thread(thread3).start(); } } //下载图片类 class WebDownload{ public void download(String url,String filename){ try { //下载图片并重命名 FileUtils.copyURLToFile(new URL(url),new File(filename)); } catch (IOException e) { e.printStackTrace(); } } }