interrupt 停止线程

  该方法只是给线程设置了一个停止的标记 并不是真正的立即停止线程

  interrupted() 测试当前线程是否已经中断
  isInterrupted() 测试线程是否已经中断
  停止线程的方法:

1.异常法 (相当于return出去)
package entity.thread;

public class Mythread extends Thread{

@Override
public void run() {
super.run();
try {
for(int i=0;i<500000;i++){
if(this.interrupted()){
System.out.println("是停止状态了。。。");
throw new InterruptedException();
}
System.out.println("i=" + (i+1));
}
System.out.println("我在for下面");
} catch (InterruptedException e) {
System.out.println("进入异常方法了线程终止");
e.printStackTrace();
}
}


public static void main(String[] args) throws InterruptedException {
try {
Mythread mh = new Mythread();
mh.start();
mh.sleep(2000);
mh.interrupt();
} catch (Exception e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end");

}
}

打印结果:
i=223322
i=223323
end
是停止状态了。。。
进入异常方法了线程终止
java.lang.InterruptedException
at entity.thread.Mythread.run(Mythread.java:12)

2.在沉睡中被停止 (程序会直接抛异常)
package entity.thread;

public class Mythread2 extends Thread{

@Override
public void run() {
super.run();
try {
System.out.println("run begin");
Thread.sleep(200000);
System.out.println("run end");
} catch (InterruptedException e) {
System.out.println("在沉睡中被终止! 进入catch!"+ this.isInterrupted());
e.printStackTrace();
}
}
public static void main(String[] args) {
try {
Mythread2 mythread2 = new Mythread2();
mythread2.start();
mythread2.sleep(200);
mythread2.interrupt();
} catch (InterruptedException e) {
System.out.println("main catch");
e.printStackTrace();
}
System.out.println("end");
}
}
执行结果
run begin
end
在沉睡中被终止! 进入catch!false
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at entity.thread.Mythread2.run(Mythread2.java:10)

 

3.暴力停止 stop 方法 已经过时不建议使用并且会存在问题

posted on 2019-06-04 22:51  gfaraway  阅读(475)  评论(0编辑  收藏  举报

导航