实现runnable接口

实现runnable接口

package test1;

public class TestThread3 implements Runnable {
    //主线程,main线程
    public static void main(String[] args) {
        //创建一个runnable实现接口对象
        TestThread3 testThread3=new TestThread3();
        //创建线程对象,调用start()
        new Thread(testThread3).start();

        for (int i = 0; i < 10; i++) {
            System.out.println("main线程学习"+i);
        }
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("run线程学习"+i);
        }
    }
}

例子:

package test1;

import org.apache.commons.io.FileUtils;

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

//实现多线程下载图片
public class TestThread4 implements Runnable{
    private String url;
    private String filename;

    public TestThread4(String url,String filename){
        this.url=url;
        this.filename=filename;
    }

    @Override
    public void run() {
        WDownloader wDownloader=new WDownloader();
        wDownloader.downloader(url,filename);
        System.out.println("图片下载结束名字为"+filename);
    }



    public static void main(String[] args) {
        TestThread4 t1=new TestThread4("https://msdn.itellyou.cn/images/itellyou.cn.png","11.jpg");
        TestThread4 t2=new TestThread4("https://msdn.itellyou.cn/images/20200323140428-min.png","22.jpg");
        TestThread4 t3=new TestThread4("https://www.kuangstudy.com/assert/images/index_topleft_logo.png","33.jpg");

        new Thread(t1).start();
        new Thread(t2).start();
        new Thread(t3).start();

    }
}

//下载器
class WDownloader{
    //下载方法
    public void  downloader(String url,String filename){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(filename));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("io异常");
        }
    }
}

上一篇:VLC web(http)控制 (4) 服务器文件获取


下一篇:JavaSE 线程知识点学习整理