java基礎實現多執行緒下載圖片
阿新 • • 發佈:2022-11-29
通過繼承Thread實現執行緒
第一步匯入commons-io jar包,裡面已經封裝好了工具,可以直接使用
首先建立一個圖片下載方法
class WebDownload{ //下載方法 public void downloader(String url,String name){ try { FileUtils.copyURLToFile(new URL(url),new File(name)); } catch (IOException e) { throw new RuntimeException(e); } } }
具體實現
public class TestThread extends Thread{ private String url; private String name; public TestThread(String url,String name){ this.url=url; this.name=name; } @Override public void run() { WebDownload webDownload = new WebDownload(); webDownload.downloader(url,name); System.out.println("下載了檔案為:"+name); } public static void main(String[] args) { TestThread t1 = new TestThread("https://i01piccdn.sogoucdn.com/aa9f24026a5cbd65","1.jpg"); TestThread t2 = new TestThread("https://i01piccdn.sogoucdn.com/166d76632f06b0ce","2.jpg"); TestThread t3 = new TestThread("https://i01piccdn.sogoucdn.com/aa9f24026a5cbd65","3.jpg"); TestThread t4 = new TestThread("https://i04piccdn.sogoucdn.com/d961201dbd742bbc","4.jpg"); t1.start(); t2.start(); t3.start(); t4.start(); } }