线程生命周期详解
一、线程和进程
进程: 应用程序的执行实例
有独立的内存空间和系统资源
线程: cpu调度和分派的基本单位
进程中执行运算的最小单位,可以完成一个独立的顺序控制流 程
二、什么是多线程
1、如果在一个进程中同时运行多个线程,用来完成不同的工作,则称之为多线程
2、多个线程 交替 占用cpu资源,而非真正的并行执行
多线程的好处
充分利用cpu的资源
简化编程模型
带来良好的用户体验
三、线程的创建和使用
常用的两种方法
继承Thread类
实现Runnable接口
使用线程的步骤
定义线程 创建线程对象 启动线程 终止线程
1、继承Thread类
/**
* @Author 张航
* @Date 2024/7/8
* @Description 创建多线程的第一种方法
*/
public class MyThread extends Thread {
@Override
public void run(){
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+":"+i+"次");
}
}
}
/**
* @Author 张航
* @Date 2024/7/8
* @Description
*/
public class test {
public static void main(String[] args) {
//创建自定义线程类对象
MyThread myThread = new MyThread();
myThread.setName("A");
MyThread myThread1 = new MyThread();
myThread1.setName("B");
//通过线程直接调用run方法是由主线程来执行的
//通过start方法是通过主线程和子线程并行交替执行
myThread1.start();
myThread.start();
}
}
2、实现Runnable接口
/**
* @Author 张航
* @Date 2024/7/8
* @Description 实现Runnable接口
*/
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+":"+i+"次");
}
}
}
/**
* @Author 张航
* @Date 2024/7/8
* @Description
*/
public class test {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
//myRunnable类中没有start()方法, 父类Object类中也没有
Thread thread = new Thread(myRunnable);
thread.start();
}
}
优先级
优先级由1-10表示
1最低,默认优先级为5
设置优先级,优先级高的线程比优先级低的线程获取cpu资源的概率更高
四、线程的生命周期
5、线程休眠
import org.w3c.dom.ls.LSOutput;
/**
* @Author 张航
* @Date 2024/7/8
* @Description
*/
public class sleep {
public static void main(String[] args) throws InterruptedException {
System.out.println("线程开始执行");
Thread.sleep(5000);
System.out.println("线程结束执行");
}
}
6、线程强制运行
使得当前线程暂停执行,等待其他线程结束后再继续执行本线程
/**
* @Author 张航
* @Date 2024/7/8
* @Description
*/
public class test {
public static void main(String[] args) {
MyJoin myJoin = new MyJoin();
Thread thread = new Thread(myJoin,"AA");
thread.start();
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+":"+i+"次");
if (i==5){
try {
//强制执行线程 会暂停当前线程
thread.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
7、线程礼让
暂停当前线程,允许其他具有相同优先级的线程获得运行机会
该线程处于就绪状态,不转为阻塞状态
只是提供一种可能,但是不能保证一定会实现礼让
(因为他暂停之后到了 就绪状态还会继续和其他线程一起抢占)
}
}
}
}
}
##### 7、线程礼让
暂停当前线程,允许其他具有相同优先级的线程获得运行机会
该线程处于就绪状态,不转为阻塞状态
只是提供一种可能,但是不能保证一定会实现礼让
(因为他暂停之后到了 就绪状态还会继续和其他线程一起抢占)