多线程名称概念
名词 | 定义(概念) | 静态(动态) | 调用者 |
---|---|---|---|
程序 | 指令和数据的集合 | 静态 | - |
进程 | 执行程序的一次执行过程 | 动态 | 系统资源分配的单位 |
线程 | 进程中的独立的运行路径 | 动态 | 调度器(CPU)进行安排调用 |
注意点:
- 进程至少包含一个线程
- 一个进程有多个线程情况,线程的执行由CPU调用执行,线程之间异步运行
Thread入门
创建线程方式的有三种,其中之一就是通过Thread创建线程
Thread创建线程分三步:
- 自定义类继承Thread类
- 自定义类重写Thread类的run方法
- 创建自定义类对象,执行start方法,开启线程
Demo案例:
自定义类代码:
package thread.learn;
public class CustomThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("自定义线程运行" + i);
}
}
}
运行类代码:
package thread.learn;
public class RunCustomThread {
public static void main(String[] args) {
CustomThread ct = new CustomThread();
ct.start();
for (int i = 0; i < 100; i++) {
System.out.println("执行主线程" + i);
}
}
}
运行结果:
运行结果证明:主线程和自定义线程是异步的
Thread练习
题目:使用多线程,异步下载多个图片(下载工具可以引入:commons-io.jar包)
自定义线程类:
package thread.learn;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.FileUtils;
public class DownWebPicture extends Thread {
private String url;
private String fileName;
public DownWebPicture(String url, String fileName) {
this.url = url;
this.fileName = fileName;
}
@Override
public void run() {
try {
System.out.println("下载图片:" + fileName);
FileUtils.copyURLToFile(new URL(url), new File(fileName));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行类:
package thread.learn;
public class RunDownWebPicture {
public static void main(String[] args) {
DownWebPicture downWebPicture1 = new DownWebPicture(
"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201908%2F12%2F20190812160130_4fURK.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1727062038&t=90146e361bc57f048e873103d585bdcc",
"美女1.jpg");
DownWebPicture downWebPicture2 = new DownWebPicture(
"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201908%2F12%2F20190812160130_4fURK.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1727062038&t=90146e361bc57f048e873103d585bdcc",
"美女2.jpg");
DownWebPicture downWebPicture3 = new DownWebPicture(
"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F201908%2F12%2F20190812160130_4fURK.jpeg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1727062038&t=90146e361bc57f048e873103d585bdcc",
"美女3.jpg");
downWebPicture1.start();
downWebPicture2.start();
downWebPicture3.start();
}
}
运行结果: