Runnable小练习(网图下载)
Posted 小郑要做干饭人
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Runnable小练习(网图下载)相关的知识,希望对你有一定的参考价值。
package com.zzx.线程.Runnable;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
/**
* @date: 2022/08/10/ 22:55
* @author: ZhengZiXuan
* @title: 练习Thread,实现一个多线程同步下载图片
* @description:
*/
public class RunnablePractise implements Runnable
//网络图片地址
private String url;
//保存的文件名
private String name;
@Override
public void run()
WebDownloader webDownloader = new WebDownloader();
webDownloader.downLoader(url,name);
System.out.println("下载了文件名为:"+name);
public RunnablePractise(String url,String name)
this.name=name;
this.url = url;
public static void main(String[] args)
RunnablePractise t1 = new RunnablePractise("https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2021%2F0731%2Fe91198a9j00qx35q30050c000j600nym.jpg&thumbnail=660x2147483647&quality=80&type=jpg","小姐姐1.jpg");
RunnablePractise t2 = new RunnablePractise("https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2020%2F0308%2Faa2f8437j00q6uv1c001fc000hs00hsm.jpg&thumbnail=660x2147483647&quality=80&type=jpg","小姐姐2.jpg");
RunnablePractise t3 = new RunnablePractise("https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2020%2F0308%2F94d8bda3j00q6uv1e000oc000hs00m7m.jpg&thumbnail=660x2147483647&quality=80&type=jpg","小姐姐3.jpg");
new Thread(t1).start();
new Thread(t2).start();
new Thread(t3).start();
//下载器
class WebDownloader
//下载方法
public void downLoader(String pictureUrl, String name)
try
FileUtils.copyURLToFile(new URL(pictureUrl),new File(name));
catch (IOException e)
e.printStackTrace();
System.err.println("IO异常,downloader方法出现问题");
控制台运行结果如下:
经过多次试验我们发现,调用start方法时,线程是同时运行的
以上是关于Runnable小练习(网图下载)的主要内容,如果未能解决你的问题,请参考以下文章