建议使用异常法,catch中可以将异常向上抛出,使得线程停止的事件可以传播
1.return 法
public class Mythread extends Thread{
public void run(){
while(true){
if(this.isInterrupted()){
//TO-DO ;
return;
}
//TO-DO;
}
}
}
public class returnMain{
public static void main(String[] args) throws InterruptException{
Mythread mt = new Mythread();
mt.start();
Thread.sleep(1000);
mt.interrput();
}
}
2.异常法
public class Mythread extends Thread{
public void run(){
try{
while(true){
if(this.isInterrupted()){
//TO-DO;
throw new InterruptException();
}
//TO-DO;
}
}catch(InterruptException e){
//TO-DO;
}
}
}
public class returnMain{
public static void main(String[] args) throws InterruptException{
Mythread mt = new Mythread();
mt.start();
Thread.sleep(1000);
mt.interrput();
}
}

本文探讨了Java中处理线程中断的两种方法:return法和异常法。通过具体代码示例,详细介绍了如何在Mythread类的run方法中检查线程是否被中断,并采取相应措施结束线程运行。
10万+

被折叠的 条评论
为什么被折叠?



