入力をブロックするメソッドを実装したいのですが、Thread.interrupt()を実行できます。たとえば、System.in.read()でブロックすると、別のスレッドがそれを中断して、InterruptedExceptionを使用してブロック読み取りから抜け出すことができます。
助言がありますか?ありがとう
入力をブロックするメソッドを実装したいのですが、Thread.interrupt()を実行できます。たとえば、System.in.read()でブロックすると、別のスレッドがそれを中断して、InterruptedExceptionを使用してブロック読み取りから抜け出すことができます。
助言がありますか?ありがとう
最初に頭に浮かぶのはBlockingQueue
. 1 つのスレッドがそのキューから smth をフェッチしようとしてハングし、別のスレッドがそのキューに要素を入力します。たとえば、読み取りを実行するスレッドが要素をSystem.in
入力BlockingQueue
します。そのため、別のスレッドを中断できます。
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);
すでに別のブロッキング メソッドを待機している場合は、メソッドが InterruptedException をスローすることを宣言し、元の例外をキャッチしないようにします。それとも何か他のものを求めていますか?