多线程实现Runnable接口

2021/4/8 18:25:19

本文主要是介绍多线程实现Runnable接口,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

多线程实现Runnable接口

因为java是单继承,这个是弥补单继承的不足

启动多线程的方式不一样,需要new Thread().start(); new Thread因为Thread实现了Runnable接口

package com.lening.thread;

import org.apache.commons.io.FileUtils;

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

/**
 * @Author WangEn
 * @CreateTime: 2021-04-08-09-21
 * @Emile: wen_5988@163.com
 */
public class TestRunnable implements Runnable {

    private String url;
    private String name;

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

    @Override
    public void run() {
        try {
            try {
                new Thread().sleep(100000000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            new WebDownLoader().WebDownLoader(url, name);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            System.out.println("Io异常,下载失败");
        }
    }

    public static void main(String[] args) {
        //new Thread(new TestThread("https://img1.baidu.com/it/u=1485012388,2380514454&fm=26&fmt=auto&gp=0.jpg", "1.jpg")).start();
        new Thread(new TestThread("https://img2.baidu.com/it/u=3355464299,584008140&fm=26&fmt=auto&gp=0.jpg", "2.jpg")).start();
        //new Thread(new TestThread("https://img1.baidu.com/it/u=2496571732,442429806&fm=26&fmt=auto&gp=0.jpg","3.jpg")).start();
    }

}

/**
 * 下载工具
 */
class WebDownLoader {
    public void WebDownLoader(String url, String name) throws MalformedURLException {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}



这篇关于多线程实现Runnable接口的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程