调用stop方法
Stop:中止线程,并且清除监控器锁的信息,但是可能导致 线程安全问题,JDK不建议用。 Destroy: JDK未实现该方法。
Interrupt(线程中止)
Interrupt 打断正在运行或者正在阻塞的线程。
1.如果目标线程在调用Object class的wait()、wait(long)或wait(long, int)方法、join()、join(long, int)或sleep(long, int)方法时被阻塞,那么Interrupt会生效,该线程的中断状态将被清除,抛出InterruptedException异常。
2.如果目标线程是被I/O或者NIO中的Channel所阻塞,同样,I/O操作会被中断或者返回特殊异常值。达到终止线程的目的。
如果以上条件都不满足,则会设置此线程的中断状态。
打断正在阻塞的线程
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
}, “t1”);
t1.start();
try {
Thread.sleep(1000);
} catch (Exception e) {
}
System.out.println("打断子线程");
//调用interrupt 打断正在阻塞的线程
t1.interrupt();
System.out.println("获取打断标记:" + t1.isInterrupted());
}
打断正在运行的线程
public class Thread06 extends Thread {
@Override
public void run() {
while (true) {
// 如果终止了线程,则停止当前线程
if (this.isInterrupted()) {
break;
}
}
}
public static void main(String[] args) {
Thread06 thread06 = new Thread06();
thread06.start();
try {
Thread.sleep(1000);
} catch (Exception e) {
}
thread06.interrupt();
}
}