中斷處理
在java程式中,當使用Thread.sleep()或者BlockingQueue.take()等阻塞方法時,需要處理InterruptedException。對於這種異常,通常有2種方案進行處理。
1. 傳遞異常:將異常傳遞給方法的調用者。樣本如下:
BlockingQueue<String> queue;public String getNextString() throws InterruptedException{return queue.take();}
2. 恢複異常:在大多數情況下,異常是可以傳遞的,但有些情況是無法傳遞異常的,比如在Runnable的run()方法中,我們不可以拋出異常。此時需要我們恢複異常,這樣在調用棧中更高層次的代碼將看到引發了一個中斷。樣本如下:
BlockingQueue<String> queue;public String getNextString() throws InterruptedException{String result=null; try{result=queue.take();}catch(InterruptedException e){Thead.currentThread.interrupt();}finally{Return result;}}
以上是處理InterruptedException的常用方法,對於InterruptedException,千萬不要捕獲異常但不做任何處理。 當我們使用中斷來結束線程時,在catch塊中也可以使用interrupted()來清除異常。
任務取消
多線程編程時,有時候需要取消某些任務線程,有以下3種方案:
1. 設定一個線程取消的標記,任務線程週期性檢查這個標記。樣本如下:
class Task implements Runnable{private volatile boolean cancel=false;@Overridepublic void run() {while(!cancel){System.out.println("...");}}public void cancel(){cancel=true;}}2. 上面的樣本描述的是最一般的情境,試想一下,如果while(!cancel)迴圈中調用了一個阻塞的方法,那麼有這樣一種可能:程式可能阻塞在某個方法中。樣本如下:
class Task implements Runnable{private volatile boolean cancel=false;private BlockingQueue<String> blockingQueue;public Task(BlockingQueue<String> queue){this.blockingQueue=queue;}@Overridepublic void run() {try{while(!cancel){System.out.println("...");this.blockingQueue.take();//當程式阻塞在此處時,即便cancel被更新了,也無法感知,這種情況下,程式永遠無法退出。}}catch(InterruptedException e){Thread.currentThread().interrupt();}}public void cancel(){cancel=true;}}
當while(!cancel)迴圈中調用了一個阻塞的方法時,使用標記位的方式終止程式就不再使用了,此時使用中斷的方式退出程式:
import java.lang.reflect.Method;import java.util.HashMap;import java.util.Map;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;public class CDemo { public static void main(String [] args) throws Exception{ BlockingQueue<String> b=new ArrayBlockingQueue<String>(3); b.put("a"); b.put("ab"); b.put("abc"); Task task=new Task(b); task.start(); Thread.sleep(4000); task.cancel(); }}class Task extends Thread{ private BlockingQueue<String> blockingQueue; public Task(BlockingQueue<String> queue){ this.blockingQueue=queue; } @Override public void run() { try{ while(true){// if(Thread.currentThread().isInterrupted()) //一定注意,這行是錯誤做法 if(interrupted())//判斷當前線程是否被中斷 break; String str=this.blockingQueue.take(); System.out.println(str); } }catch(InterruptedException e){ //Thread.currentThread().interrupt(); interrupted();//清除中斷痕迹 }finally{ System.out.println("線程結束。"); } } public void cancel(){ this.interrupt();//中斷當前線程// Thread.currentThread().interrupt(); //一定注意,這行是錯誤做法 } }
3. 在生產者消費者問題中,使用“毒丸對象”來終止消費者線程。
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.CountDownLatch;public class Coordinator {public static final Object POISON_PILL = new Object();//special object to kill consumersprivate int productCount = 1;private int consumerCount = 3;public void startAll() throws Exception{BlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(5);CountDownLatch activeProductorNum = new CountDownLatch(productCount);CountDownLatch activeConsumerNum = new CountDownLatch(consumerCount);for(int i = 0; i < consumerCount; i++){new Thread(new Consumer("consumer " + i, queue,activeConsumerNum)).start();}for(int i = 0; i < productCount; i++){new Thread(new Producer("producer " + i, queue, activeProductorNum)).start();}activeProductorNum.await();//等待所有生產者生產結束System.out.println("All producer finished, putting POISON_PILL to the queue to stop consumers!");queue.put(POISON_PILL);activeConsumerNum.await();//等待所有生產者生產結束System.out.println("All consumer finished!");}public static void main(String[] args) throws Exception{new Coordinator().startAll();}}class Producer implements Runnable {private String name;private BlockingQueue<Object> queue;private CountDownLatch activeProducerNum;public Producer(String name, BlockingQueue<Object> queue, CountDownLatch activeProducerNum){this.name = name;this.queue = queue;this.activeProducerNum=activeProducerNum;}@Overridepublic void run() {try {for(int i=0;i<10;i++){queue.put(i);System.out.println(name + " produced "+i);}} catch (InterruptedException e) {Thread.currentThread().interrupt();} finally{System.out.println(name + " finished.");activeProducerNum.countDown();}}}class Consumer implements Runnable {private String name;private BlockingQueue<Object> queue;private CountDownLatch activeConsumerNum;public Consumer(String name, BlockingQueue<Object> queue,CountDownLatch activeConsumerNum){this.name = name;this.queue = queue;this.activeConsumerNum=activeConsumerNum;}@Overridepublic void run() {try {while (true) {Object item = queue.take();if (item == Coordinator.POISON_PILL) {queue.put(item);//放回繼續毒害其他消費者break;}System.out.println(name + " consumed "+item);}} catch (InterruptedException e) {Thread.currentThread().interrupt();} finally{System.out.println(name + " finished");activeConsumerNum.countDown();}}}