案例:下载图片

先下载工具类库,网上搜common-io-2.6.jar,拷到项目里,新建一个package叫lib

右键-->add as library

image-20210928222947613

这样就能用了,在项目结构里也能看到

image-20210928223030941

这个类就是刚才导的包里的

image-20210928223647413

扒图片url

image-20210928224658438

image-20210928225457838

image-20210928225512941

运行

image-20210928225607259

按123写的代码,但是按321运行的,每次运行的结果可能不一样

image-20210928225834246

所以线程不一定立即执行,通过CPU安排调度,通过start方法启动线程

多线程P04结束


来源:b站狂神

package com.yuan.demo01;


import org.apache.commons.io.FileUtils;

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

//练习Thread,实现多线程同步下载图片
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 t1 = new TestThread2("https://game.gtimg.cn/images/lol/universe/images/zaun_crest_icon.png","zuan.jpg");
        TestThread2 t2 = new TestThread2("https://game.gtimg.cn/images/lol/universe/images/ixtal_crest_icon.png","yixutaer.jpg");
        TestThread2 t3 = new TestThread2("https://game.gtimg.cn/images/lol/universe/images/demacia_crest_icon.png","demaxiya.jpg");
        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("IO异常,downLoader方法出现问题");
        }
    }
}

 

posted on 2021-09-28 23:02  托马斯源  阅读(43)  评论(0编辑  收藏  举报