1. 程式人生 > 實用技巧 >實現多執行緒同步下載檔案

實現多執行緒同步下載檔案

public class Thread2 extends Thread {
//網路地址
private String url;
//儲存的檔名
private String name;
//建構函式
public Thread2(String url, String name) {
this.url = url;
this.name = name;
}
//3、下載檔案的執行緒執行體
@Override
public void run() {
FileDownLoader fileDownLoader = new FileDownLoader();
fileDownLoader.downLoader(url,name);
System.out.println("下載了檔名為:" + name);
}
//4、主執行緒執行
public static void main(String[] args) {
Thread2 t1 = new Thread2("

https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1887333225,3220403259&fm=26&gp=0.jpg","紫霞仙子.jpg");
Thread2 t2 = new Thread2("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1115306696,372850764&fm=26&gp=0.jpg","冰霜戀舞曲.jpg");
Thread2 t3 = new Thread2("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3005655293,1504161907&fm=26&gp=0.jpg","元素使.jpg
");
//開啟執行緒
t1.start();
t2.start();
t3.start();
}
}
//2、下載器
class FileDownLoader{
// 下載方法
public void downLoader(String url,String name) {
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO異常:downLoader方法出錯");
}
}
}