package com.thread.killthread;
/**
* 用中断的方式杀死线程
*/
public class InterruptToKillThread extends Thread{
@Override
public void run() {
//中断方式1
// while (true){
// System.out.println("I am working");
// if (Thread.interrupted()){
// break;
// }
// }
//中断方式2
while (true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;//return;
}
}
}
//结束线程
public void killThread(){
this.interrupt();
}
}
class InterruptToKillThreadTest{
public static void main(String[] args) {
InterruptToKillThread interruptToKillThread = new InterruptToKillThread();
interruptToKillThread.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
interruptToKillThread.killThread();
}
}
结束线程的方式二
最新推荐文章于 2022-08-12 09:21:11 发布