2012-12-03 35 views
0

我想實現一個方法阻塞輸入,但可以是Thread.interrupt()'ed。例如,它阻塞System.in.read(),然後另一個線程可以中斷它,以便突破阻塞讀取,並帶有InterruptedException。執行一個可中斷的方法

有什麼建議嗎? 謝謝

回答

1

首先想到的是BlockingQueue。一個線程將掛起,試圖從該隊列中獲取smth,而另一個線程將使用元素填充該隊列,例如,執行從System.in讀取的線程將使用元素填充BlockingQueue。所以另一個線程可以被中斷。

0

如果它已經在等待另一個阻塞方法,只需將您的方法聲明爲拋出InterruptedException並且不捕獲原始異常。還是你要求別的東西?

1

考慮java.nio.InterruptibleChannel

If a thread is blocked in an I/O operation on an interruptible channel then another thread may invoke the blocked thread's interrupt method. This will cause the channel to be closed, the blocked thread to receive a ClosedByInterruptException, and the blocked thread's interrupt status to be set. 

這裏是如何「可中斷」從文件中讀取數據

FileChannel ch = new FileInputStream("test.txt").getChannel(); 
    ByteBuffer buf = ByteBuffer.allocate(1024); 
    int n = ch.read(buf); 

時被另一個線程中斷「讀」會拋出ClosedByInterruptException,它是IOException的一個實例。

這裏是如何「可中斷」從TCP服務器讀取的字節

SocketChannel ch = SocketChannel.open(); 
    ch.connect(new InetSocketAddress("host", 80)); 
    ByteBuffer buf = ByteBuffer.allocate(1024); 
    int n = ch.read(buf);