文章目录
3种方法停止线程
在Java中有以下3种方法可以终止正在运行的线程:
- 使用退出标志,使线程正常退出,也就是当run方法完成后线程终止。
- 使用stop方法强行终止线程,但是不推荐使用这个方法,因为stop和suspend及resume一样,都是作废过期的方法,使用它们可能产生不可预料的结果。
- 使用interrupt方法中断线程。
判断线程是否是停止状态
在Java的SDK中,Thread.java类里提供了两种方法:
1)this.interrupted():测试当前线程是否已经中断,执行后具有将状态标志置清除为false的功能。
public static boolean interrupted()
2)this.isInterrupted():测试线程是否已经中断,但不清除状态标志。
public boolean isInterrupted()
interrupted()
this.interrupted() 方法的解释:测试当前线程是否已经中断,当前线程是指运行this.interrupted() 方法的线程。
测试案例1
public class MyThread4 extends Thread {
@Override
public void run() {
super.run();
for (int i = 0; i < 100000; i++) {
System.out.println("i=" + (i + 1));
}
}
}
public static void main(String[] args) {
try {
MyThread4 myThread4 = new MyThread4();
myThread4.start();
Thread.sleep(1000);
myThread4.interrupt();
System.out.println("是否停止1? " + myThread4.interrupted());
System.out.println("是否停止2? " + myThread4.interrupted());
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("End!");
}
输出如下:
...
i=18442
是否停止1? false
是否停止2? false
End!
...
这里强行用了myThread4对象来调用interrupted()方法。
从控制台打印的结果来看,线程并未停止,这也就证明了interrupted() 方法的解释:测试当前线程是否已经中断。这个“当前线程”是main,它从未中断过,所以打印的结果是两个false。
测试案例2
使main线程产生中断效果
public static void main(String[] args) {
Thread