本章目标
了解线程的生命周期
了解线程的停止操作
线程的生命周期
注意
大部分的线程生命周期的方法基本上都已经学过了,那么在这里有以下三个新方法:
——suspend()方法:暂时挂起线程
——resume()方法:恢复挂起的线程
——stop()方法:停止线程
但是对于线程中suspend()、resume()、stop()三个方法并不推荐使用,因为这三个方法在操作的时候会产生死锁的问题。
停止线程运行
既然以上的三个方法不推荐使用,那么该如何停止一个线程的执行呢?在多线程的开发中可以通过设置标志位的方式停止一个线程的运行。
停止线程运行
class MyThread implements Runnable {
private boolean flag = true; // 定义标志位属性
public void run() { // 覆写run()方法
int i = 0;
while (this.flag) { // 循环输出
while (true) {
System.out.println(Thread.currentThread().getName() + "运行,i = " + (i++)); // 输出当前线程名称
}
}
}
public void stop() { // 编写停止方法
this.flag = false; // 修改标志位
}
}
public class StopDemo {
public static void main(String[] args) {
MyThread my = new MyThread(); // 实例化Runnable接口对象
Thread t = new Thread(my, "线程"); // 建立线程对象
t.start() ; // 启动线程
my.stop() ; // 线程停止,修改标志位
}
/* 结果:
*
* */
}