1. 程式人生 > 其它 >Thread多執行緒寫網圖下載

Thread多執行緒寫網圖下載

技術標籤:java多執行緒

如果不懂Thread的話,可以看我的上一篇文章,

package oop.網圖下載;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

//多執行緒同步下載圖片
public class testhread1 extends Thread {

    private String name;//網路圖片地址
    private String url;//儲存的檔名

    //構造方法
    public
testhread1(String name, String url) { this.name = name; this.url = url; } //重寫run()方法 //下載圖片執行緒的執行體 @Override public void run() { WebDownloader webDownloader = new WebDownloader(); webDownloader.downloader(url, name); System.out.println("下載了檔名為:"
+ name); } public static void main(String[] args) { testhread1 t1 = new testhread1("1.png", "https://www.woyaogexing.com/tupian/weimei/"); testhread1 t2 = new testhread1("2.png", "https://www.woyaogexing.com/tupian/weimei/"); testhread1 t3 =
new testhread1("3.png", "https://www.woyaogexing.com/tupian/weimei/"); t1.start(); t2.start(); t3.start(); } } //寫檔案下載工具類 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("檔案下載失敗!!!"); } } }

在這裡插入圖片描述
這是執行之後的圖片。

【以上程式要匯入commons.io.jar包,網頁下載或者私聊我即可,在lib中配置一下就行】