java线程中断方式
java线程停止的几种情况:
1、Thread 运行完自然结束
2、Thread.stop() 不推荐使用,会产生不可预料的错误
3、Thread.interrupt() 实际上是打个标记,并不是真正的停止线程。
Thread.interrupt() 之后 Thread.isInterrupted() 变为false这样可以进行相应的操作达到线程停止的目的
可以通过抛出异常的方式执行跳过run方法里面程序,仅仅通过if判断 if后面的语句还会执行
总结: 通过调用interrupt方法将 isInterrupt变成true 然后在run方法中判断 isInterrupt 执行相应操作达到中断的目的。
- Thread.interrupt() 方法:将标记位变成 true
- Thread.interrupted() 方法:清除interrupt操作,即Thread.isInterrupt变为false
- Thread.isInterrupt() 方法:返回标记位,可在run方法中通过判断执行系列操作达到中断线程的目的。
// 1、Thread 运行完自然结束
// 2、Thread.stop() 不推荐使用,会产生不可预料的错误
// 3、Thread.interrupt() 实际上是打个标记,并不是真正的停止线程。
// Thread.interrupt() 之后 Thread.isInterrupted() 变为false这样可以进行相应的操作达到线程停止的目的
// 可以通过抛出异常的方式执行跳过run方法里面程序,仅仅通过if判断 if后面的语句还会执行
import org.junit.Test;
class MyThread3 extends Thread {
@Override
public void run() {
System.out.println("run 执行。。。。。。。");
if (this.isInterrupted()) {
System.out.println("this.isInterrupted() :" + this.isInterrupted());
}
System.out.println("我是interrupt之后的语句");
for (int i = 0; i < 50000; i++) {
if (this.isInterrupted()) {
System.out.println("判断 this.isInterrupted()=true 执行相应语句");
break;
}
System.out.println(i);
}
System.out.println("我是for循环之后的语句");
}
}
class MyThread3_1 extends Thread {
@Override
public void run() {
try {
for (int i = 0; i < 50000; i++) {
if (this.isInterrupted()) {
throw new InterruptedException("通过if判断 是否中断 如果中断则抛出异常");
}
System.out.println(i);
}
System.out.println("我是for循环之后的语句。。。");
} catch (InterruptedException e) {
System.out.println(e);
System.out.println("捕捉异常,中断线程执行(通过跳过执行run方法中内容方式)");
}
}
}
public class StudyThreads3线程中断 {
public static void main(String[] args) {
Thread thread = new MyThread3();
thread.start();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread.interrupt() 执行之前:" + thread.isInterrupted());
thread.interrupt();
System.out.println("thread.interrupt() 执行之后:" + thread.isInterrupted());
System.out.println("======================================");
}
@Test
public void test() {
Thread myThread3_1 = new MyThread3_1();
myThread3_1.start();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("myThread3_1.interrupt() 执行之前:" + myThread3_1.isInterrupted());
myThread3_1.interrupt();
System.out.println("myThread3_1.interrupt() 执行之后:" + myThread3_1.isInterrupted());
}
}
线程睡眠时候执行interrupt、interrupt之后线程睡眠抛出异常 InterruptException
线程睡眠时候执行interrupt、interrupt之后线程睡眠抛出异常 InterruptException
stop方式
暴力方式结束线程
- 会抛出ThreadDeath异常,一般不需要显示捕捉异常
缺点:
- 清理工作得不到完成
- 对锁定对象进行“解锁”,数据得不到同步处理,出现数据不一致的问题
使用return停止线程
- 使用interrupt与return相互配合达到停止线程的目的。
@Override
public void run() {
while (true){
System.out.println(System.currentTimeMillis());
if (this.isInterrupt()){
return;
}
}
}
- 一般使用抛出异常捕捉异常的方式停止进程,更加方便的控制程序的运行流程