多线程实现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();
}
}
}

浙公网安备 33010602011771号