Thread.stop, Thread.suspend, Thread.resume 和Runtime.runFinalizersOnExit 這些終止線程運作的方法已經被廢棄,使用它們是極端不安全的!
1.線程正常執行完畢,正常結束
也就是讓run方法執行完畢,該線程就會正常結束。
但有時候線程是永遠無法結束的,比如while(true)。
2.監視某些條件,結束線程的不間斷運作
需要while()循環在某以特定條件下退出,最直接的辦法就是設一個boolean标志,并通過設定這個标志來控制循環是否退出。
public class ThreadFlag extends Thread {
public volatile boolean exit = false;
public void run() {
while (!exit) {
System.out.println("running!");
}
}
public static void main(String[] args) throws Exception {
ThreadFlag thread = new ThreadFlag();
thread.start();
sleep(); // 主線程延遲5秒
thread.exit = true; // 終止線程thread
thread.join();
System.out.println("線程退出!");
}
}
3.使用interrupt方法終止線程
如果線程是阻塞的,則不能使用方法2來終止線程。
public class ThreadInterrupt extends Thread {
public void run() {
try {
sleep(); // 延遲50秒
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) throws Exception {
Thread thread = new ThreadInterrupt();
thread.start();
System.out.println("在50秒之内按任意鍵中斷線程!");
System.in.read();
thread.interrupt();
thread.join();
System.out.println("線程已經退出!");
}
}
學習Java的同學注意了!!!
學習過程中遇到什麼問題或者想擷取學習資源的話,歡迎加入Java學習交流群,群号碼:286945438 我們一起學Java!