stop()方法已經(jīng)被棄用,原因是不太安全。API文檔中給出了具體的詳細(xì)解釋。
通過(guò)interrupted()方法打斷線程。不推薦。
通過(guò)共享變量結(jié)束run()方法,進(jìn)而停止線程。如實(shí)例
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();//已經(jīng)廢棄的方法,不建議使用,過(guò)于粗暴
//run.interrupt(); //拋出異常,但是在異常處理中寫(xiě)業(yè)務(wù)顯然不合適,不建議使用
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;
}
}
}
}