首先阐述几个关键字
1.interrupter() //线程调用,中断给当前线程设置中断标记(并非立即中断线程)
2.interrupted()//静态方法 调用该方法返回当前线程是否终止 该方法具有清除终止状态的功能
3.isInterrupted()//线程实例调用,返回线程实力是否终止
利用终止关键字完成《异常法终止线程》
public class demo2 {
public static void main(String[] args){
try {
MyThread myThread = new MyThread();
myThread.start();
Thread.sleep(1000);
myThread.interrupt();//设置想成中断标记
/*Thread.currentThread().interrupt();
System.out.println(Thread.interrupted());
System.out.println(Thread.interrupted());
System.out.println(Thread.interrupted());*/
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class MyThread extends Thread{
@Override
public void run() {
try{
for (int i = 0; i < 200000; i++) {
if(this.isInterrupted()){//测试线程是否有中断标记 同效于Thread.isInterrupted()
System.out.println("for end");
throw new InterruptedException();//此处可以用return;
}
System.out.println(i);
}
System.out.println("for之后代码标识线程未停止");
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
【注:抛异常出可以使用return,不过抛异常的好处是进入catch块,可以上抛异常,使线程停止的事件得以传播】