Java沒有安全的搶占方法來停止線程,只有協作式的機制,使代碼遵循一種協商好的協議來提前結束線程。
其中一種協作機制是通過設置標志(已請求取消),任務將定期查看該標志,如果設置了該標志,則任務提前結束。
例如我們可以通過volatile類型域(關于volatitle類型域的特點和作用本篇不做介紹,不了解的同學可以自行搜索)來取消,設置變量private volatile boolean cancelled = false;
在任務中循環判斷cancelled來跳出循環
private volatile boolean cancelled = false;
while(!cancelled){
System.out.println(" queue.put 1");
queue.put(p = p.nextProbablePrime());
System.out.println(" queue.put 2");
}
public void cancel(){
// interrupt();
cancelled = true;
System.out.println(" cancel ");
}
但如果使用這個方法的任務中調用了阻塞方法,可能會因為阻塞而存在代碼永遠不會執行到檢查標志位的地方,因此永遠不會結束(一直卡在阻塞位置)
LOG如下:
queue.put 1
queue.put 2
queue.put 1
queue.put 2
queue.put 1
queue.put 2
queue.put 1
queue.put 2
queue.put 1
consume value = 2
cancel
所以保險情況是通過中斷來取消
完整代碼如下
package com.thread.test.interrupt;
import java.math.BigInteger;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import static java.util.concurrent.TimeUnit.SECONDS;
public class PrimeProducer extends Thread {
private final BlockingQueue<BigInteger> queue;
private volatile boolean cancelled = false;
public PrimeProducer(BlockingQueue<BigInteger> queue) {
// TODO Auto-generated constructor stub
this.queue = queue;
}
public void run() {
try{
BigInteger p = BigInteger.ONE;
// // volatile類型域
// while(!cancelled){
// System.out.println(" queue.put 1");
// queue.put(p = p.nextProbablePrime());
// System.out.println(" queue.put 2");
// }
// while(!Thread.currentThread().isInterrupted()){
// System.out.println(" queue.put 1");
// queue.put(p = p.nextProbablePrime());
// System.out.println(" queue.put 2");
// }
while(true){
if(Thread.currentThread().isInterrupted()){
System.out.println(" isInterrupted ");
break;
}
System.out.println(" queue.put 1");
queue.put(p = p.nextProbablePrime());
System.out.println(" queue.put 2");
}
}catch(InterruptedException e){
System.out.println(" InterruptedException e");
}
}
public void cancel(){
interrupt();
// cancelled = true;
System.out.println(" cancel ");
}
public static boolean needMroePrime(int count){
if(count >= 1){
return false;
}else{
return true;
}
}
public static void consume(BigInteger value){
System.out.println(" consume value = "+value);
}
public static void main(String[] args) {
final BlockingQueue<BigInteger> prime = new ArrayBlockingQueue<BigInteger>(3);
PrimeProducer producer = new PrimeProducer(prime);
producer.start();
int count = 0;
try{
SECONDS.sleep(1);
while(needMroePrime(count)){
count++;
consume(prime.take());
}
}catch(InterruptedException e){
}finally{
producer.cancel();
}
}
}
程序運行結果示例:
queue.put 1
queue.put 2
queue.put 1
queue.put 2
queue.put 1
queue.put 2
queue.put 1
queue.put 2
queue.put 1
consume value = 2
cancel
InterruptedException e
從LOG執行情況我們可以看到,線程雖然還是阻塞在put方法中,但還是通過拋出異常而退出,進一步查看源碼我們可以發現在BlockingQueue的put方法中會拋出InterruptedException異常,并注明 InterruptedException if interrupted while waiting
(繼續深入源碼可以發現阻塞實際是一個while循環不斷執行,再循環中會判斷Thread.interrupted(),中斷則拋出InterruptedException, AbstractQueuedSynchronizer$ConditionObject)
另外一些阻塞庫方法,例如Thread.sleep和Object.wait等,都會檢查線程何時中斷,并再發現中斷時提前返回,清除中斷狀態并拋出異常。
我們得出如下結論:
通常,中斷是實現取消最合理的方式
其他中斷線程的方法:
Thread.stop(),此方法由于嚴重的缺陷以及被廢棄,非常不建議使用,具體原因大家可自行查找
為什么要使用拋出InterruptedException的方式:
- 首先,我們再次回顧一下線程取消的概念,是讓任務提前結束,提前結束的意思可以理解線程Run方法中沒有代碼需要執行
- 線程中斷本質上也是通過判斷標志位進而拋出InterruptedException異常,拋出異常后線程實際上還沒有退出,捕獲異常之后如果直接不處理或者在Run方法中直接return則線程就被取消了,如果還有一些操作(比如例子中的打印日志),代碼還是會執行,這里可以做一些中斷策略的設計,一般我們會用來復位一些標記位,做一些資源釋放的邏輯。
- 如果不使用拋出異常的方式會怎么樣?比如在循環中我們可以通過break提前退出,再方法函數中我們可以通過return提前退出,但異常更好,異常可以不斷向上拋出(避免多個函數嵌套如果不用異常則需要不停return),只有在捕獲的地方進行處理(代碼邏輯會更清晰),甚至可以處理之后繼續向上拋出,可以非常靈活的使用,這里可以參考這篇文章 https://www.cnblogs.com/greta/p/5624839.html
附錄
Thread中的中斷方法說明
public class Thread{
public void interrupt(){...}
public boolean isInterrupted(){...}
public static boolean interrupted(){
return currentThread().isInterrupted(true);
}
// 確定線程是否被中斷,根據ClearInterrupted值決定是否重置
private native boolean isInterrupted(boolean ClearInterrupted);
}