stop()方法已經被棄用,原因是不太安全。API文檔中給出了具體的詳細解釋。
通過interrupted()方法打斷線程。不推薦。
通過共享變量結束run()方法,進而停止線程。如實例
public class ThreadInterrupt {
public static void main(String []args){
Runner run = new Runner();
run.start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
//run.stop();//已經廢棄的方法,不建議使用,過于粗暴
//run.interrupt(); //拋出異常,但是在異常處理中寫業務顯然不合適,不建議使用
run.flag=false;//建議使用的停止線程的方法
}
}
class Runner extends Thread{
boolean flag = true;
public void run(){
/* while(true){
System.out.println(new Date()+"----");
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("Interrupted");
return;
}
}
*/
while(flag){
System.out.println(new Date()+"----");
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("Interrupted");
return;
}
}
}
}