Thread类
自定义线程类继承Thread类重写run()方法,编写线程执行体创建线程对象,调用start()方法启动线程
参考代码
public class ArrayDemo10 extends Thread{
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("run方法" + i);
}
}
public static void main(String[] args) {
ArrayDemo10 ad = new ArrayDemo10();
ad.start();
for (int i = 0; i < 1000; i++){
System.out.println("main方法" + i);
}
}
}
实例:网图下载
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class Demo02 extends Thread {
private String url;
private String name;
public Demo02(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) {
Demo02 d1 = new Demo02("https://img-home.csdnimg.cn/images/20201001020546.jpg", "1.jpg");
Demo02 d2 = new Demo02("https://img-home.csdnimg.cn/images/20201001020546.jpg", "2.jpg");
Demo02 d3 = new Demo02("https://img-home.csdnimg.cn/images/20201001020546.jpg", "3.jpg");
d1.start();
d2.start();
d3.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方法出现问题");
}
}
}
转载请注明原文地址:https://blackberry.8miu.com/read-6322.html