1使用退出標志終止線程
public class ThreadSafe extends Thread {
public volatile boolean exit = false;
public void run() {
while (!exit){
//do something
}
}
}
2使用interrupt()方法終止線程(也可利用InterruptedException逃離阻塞狀態(tài))
用法:
class MyThread extends Thread {
public void run() {
try { //阻塞過程捕獲中斷異常來退出
while(!Thread.currentThread().isInterrupted()) { //非阻塞過程中通過判斷中斷標志來退出
//當達到隊列容量時,在這里會阻塞
//put的內(nèi)部會調(diào)用LockSupport.park()這個是用來阻塞線程的方法
//當其他線程罐韩,調(diào)用此線程的interrupt()方法時,會設置一個中斷標志
//LockSupport.part()中檢測到這個中斷標志娱颊,會拋出InterruptedException,并清除線程的中斷標志
//因此在異常段調(diào)用Thread.currentThread().isInterrupted()返回為false
ArrayBlockingQueue.put(somevalue);
}
} catch (InterruptedException e) {
//由于阻塞庫函數(shù)凯砍,如:Object.wait,Thread.sleep除了拋出異常外维蒙,還會清除線程中斷狀態(tài),因此可能在這里要保留線程的中斷狀態(tài)
Thread.currentThread().interrupt();
}
}
public void cancel() {
interrupt();
}
}
外部調(diào)用
MyThread thread = new MyThread();
thread.start();
......
thread.cancel();
thread.isInterrupted();