一、三种创建方式
- 继承Thread类(Thread类实现了Runnable接口)
- 实现Runnable接口
- 实现Callable接口
1.1、继承Thread类
- 自定义线程类继承Thread类
- 重写run()方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
package com.massimo.thread;
//创建线程方式一:继承Thread类,重写run方法,调用start开启线程
//注意:线程开启不一定立即执行,有cpu调度执行
public class TestThread extends Thread{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("run线程---" + i);
}
}
public static void main(String[] args) {
//main线程,主线程
//创建一个线程对象
TestThread testThread = new TestThread();
//调用start方法开启线程
testThread.start();
for (int i = 0; i < 200; i++) {
System.out.println("main线程---" + i);
}
}
}
部分效果如下:
1.2、网图下载测试
代码:
package com.massimo.thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
//实现多线程同步下载图片
public class TestThread02 extends Thread{
private String url;//网络图片地址
private String name;//保存的文件夹
public TestThread02(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) {
TestThread02 t1 = new TestThread02("https://www.apache.org/img/support-apache.jpg", "1.jpg");
TestThread02 t2 = new TestThread02("https://www.apache.org/img/support-apache.jpg", "2.jpg");
TestThread02 t3 = new TestThread02("https://www.apache.org/img/support-apache.jpg", "3.jpg");
t1.start();
t2.start();
t3.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方法出现问题");
}
}
}
效果: