什么是多线程
如果在一个进程中同时运行了多个线程,用来完成不同的工作,则称之为“多线程” 如果在一个进程中同时运行了多个线程,用来完成不同的工作,则称之为“多线程”
多个线程交替占用CPU资源,而非真正的并行执行 多个线程交替占用cpu资源,而非真正的并行执行
多线程的好处
充分利用CPU的资源简化编程模型、 充分利用cpu的资源简化编程模型、带来良好的用户体验 带来良好的用户体验
Thread类
Java提供了java.lang.Thread类支持多线程编程
主线程
main()方法即为主线程入口产生其他子线程的线程 Main()方法即为主线程入口
产生其他子线程的线程
必须最后完成执行,因为它执行各种关闭动作 必须最后完成执行,因为它执行各种关闭动作
线程中的方法
public class ThreadDemo01 {
public static void main(String[] args) {
// main()方法是程序的主入口,是一个线程
// currentThread():获取当前线程对象
Thread thread = Thread.currentThread();
// getName():获取当前线程的名称
String name = thread.getName();
System.out.println(name);
// getPriority():获取当前线程的优先级
int priority = thread.getPriority();
System.out.println("当前线程的优先级:" + priority);
// setName():设置线程的名称
thread.setName("尼古拉斯赵四");
System.out.println("线程名称:" + thread.getName());
// setPriority():设置线程优先级
thread.setPriority(8);
System.out.println("线程优先级:" + thread.getPriority());
System.out.println("线程优先级最高值:" + Thread.MAX_PRIORITY);// 10
System.out.println("线程优先级最低值:" + Thread.MIN_PRIORITY);// 1
System.out.println("线程优先级默认值:" + Thread.NORM_PRIORITY);// 5
}
}
接口方式创建线程
// 接口方式
public class MyThreadImp implements Runnable {
@Override
public void run() {
// 在重写的run()方法中编写你要执行的代码:使用循环输出1-10
for (int i = 1; i <= 10; i++) {
System.out.println(Thread.currentThread().getName() + ">" + i);
}
}
}
继承方式创建线程
// 继承方式
public class MyThread extends Thread {
// 无参构造
public MyThread() {
}
// 有参构造
public MyThread(String name) {
super(name);
}
@Override
public void run() {
// 在重写的run()方法中编写你要执行的代码:使用循环输出1-10
for (int i = 1; i <= 10; i++) {
System.out.println(Thread.currentThread().getName() + ">" + i);
}
}
}
测试类
public class Test {
public static void main(String[] args) {
// 继承方式
// 创建线程类对象
MyThread mt1 = new MyThread("第一条线程");
MyThread mt2 = new MyThread("第二条线程");
// start()方法是启动线程的方法
mt1.start();
mt2.start();
// 当同时启动两个线程以后,会出现两个线程交替占用CPU执行代码的结果
// 接口方式
MyThread mt = new MyThread();
Thread thread1 = new Thread(mt, "第三条线程");
Thread thread2 = new Thread(mt, "第四条线程");
// start()方法是启动线程的方法
thread1.start();
thread2.start();
}
}
运行结果