建议使用异常法,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();
}
}