Thread
- 自定义线程类继承
thread
类 - 重写
run()
方法 - 创建线程对象,调用
start()
方法启动线程
package Thread;
//创建线程方式一:继承thread类,然后重写run()方法,调用start执行
public class Thread01 extends Thread{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("我在看电视"+i);
}
}
public static void main(String[] args) {
//开启run方法线程
//创建一个线程对象,开启线程
Thread01 thread01 = new Thread01();
//thread01.run();
thread01.start();
//主方法,main线程
for (int i = 0; i < 20; i++) {
System.out.println("快滚去学习->"+i);
}
}
}
调用run()
只有主线程一条执行路径;
调用start()
多条执行路径,主线程和子线程并行交替执行。
实例——图片下载
在此之前,需要下载一个io包【下载地址】
添加到项目库中
总体思路:多线程下载图片,首先需要一个下载器,其中有一个下载方法,通过FileUtils工具类下的copyURLToFile方法,该方法用于把URL变成一个文件。下载好后需要去继承一个线程类,重写run()方法。通过构造器创建了三个线程,并调用start()方法。
package Thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//实现多线程同步下载图片
public class Threadexample extends Thread{
private String url; //地址
private String name; //保存的文件名
//构造器
public Threadexample(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) {
Threadexample example1 = new Threadexample("https://img-home.csdnimg.cn/images/20201125054322.jpg","offer.jpg");
Threadexample example2 = new Threadexample("https://csdnimg.cn/release/cmsfe/public/img/play.21183e07.png","UNIX.png");
example1.start();
example2.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异常,下载器方法出现问题");
}
}
}