0

入力をブロックするメソッドを実装したいのですが、Thread.interrupt()を実行できます。たとえば、System.in.read()でブロックすると、別のスレッドがそれを中断して、InterruptedExceptionを使用してブロック読み取りから抜け出すことができます。

助言がありますか?ありがとう

4

3 に答える 3

1

最初に頭に浮かぶのはBlockingQueue. 1 つのスレッドがそのキューから smth をフェッチしようとしてハングし、別のスレッドがそのキューに要素を入力します。たとえば、読み取りを実行するスレッドが要素をSystem.in入力BlockingQueueします。そのため、別のスレッドを中断できます。

于 2012-12-03T21:40:45.923 に答える
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);
于 2012-12-03T22:49:57.097 に答える
0

すでに別のブロッキング メソッドを待機している場合は、メソッドが InterruptedException をスローすることを宣言し、元の例外をキャッチしないようにします。それとも何か他のものを求めていますか?

于 2012-12-03T21:47:21.683 に答える