案例:多线程下载图片

HeJin小于 1 分钟Java多线程详解

public class TestThread2 extends Thread{

    private String url;
    private String name;

    public TestThread2(String url, String name){
        this.url = url;
        this.name = name;
    }

    /**
     * 下载图片线程的执行体
     */
    @Override
    public void run() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url, name);
        System.out.println("下载了文件名为:" + name);
    }

    public static void main(String[] args) {

        TestThread2 thread1 = new TestThread2("https://img-blog.csdnimg.cn/20210305120636825.png","1.png");
        TestThread2 thread2 = new TestThread2("https://img-blog.csdnimg.cn/20210305121018539.png","2.png");
        TestThread2 thread3= new TestThread2("https://img-blog.csdnimg.cn/20210305121930543.png","3.png");

        thread1.start();
        thread2.start();
        thread3.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("Io异常,downloader方法出现问题.");
        }
    }
}

结果:

下载了文件名为:2.png
下载了文件名为:3.png
下载了文件名为:1.png

Process finished with exit code 0