Thread提供了stop()方法終止線程,但是該方法是強行終止,容易產生一些錯誤,已經被廢棄。
可以使用退出標志來終止線程,在run()函數裡面設置while循環,把退出標志作為while的條件,當條件為false時,run函數執行完畢,線程就自動終止了。
package com.my_code.thread;
public class MyThread extends Thread {
public volatile boolean isRunning = true;
public void run(){
while (isRunning){
try {
sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void stopIt(){
isRunning = false;
}
public static void main(String[] args) throws InterruptedException{
MyThread thread = new MyThread();
thread.start();
sleep(10000);
thread.stopIt();
thread.join();
System.out.println("線程已經退出!");
}
}