Java 一种可中断方法的实现
我想实现一个方法,该方法在输入时阻塞,但可以是Thread.interrupt()'ed。例如,它在System.in.read()上阻塞,然后另一个线程可以中断它,使其中断阻塞读取,并带有InterruptedException 有什么建议吗?Java 一种可中断方法的实现,java,multithreading,Java,Multithreading,我想实现一个方法,该方法在输入时阻塞,但可以是Thread.interrupt()'ed。例如,它在System.in.read()上阻塞,然后另一个线程可以中断它,使其中断阻塞读取,并带有InterruptedException 有什么建议吗? 谢谢首先想到的是阻塞队列。一个线程将挂起,试图从该队列获取smth,而另一个线程将用元素填充该队列,例如,从系统执行读取的线程。在中,用元素填充阻塞队列。因此可以中断另一个线程。如果它已经在等待另一个阻塞方法,只需将您的方法声明为抛出Interrupt
谢谢首先想到的是
阻塞队列
。一个线程将挂起,试图从该队列获取smth,而另一个线程将用元素填充该队列,例如,从系统执行读取的线程。在
中,用元素填充阻塞队列
。因此可以中断另一个线程。如果它已经在等待另一个阻塞方法,只需将您的方法声明为抛出InterruptedException,而不捕获原始异常。还是你在要求其他东西?考虑java.nio.interruptablechannel
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);
当被另一个线程中断时,“read”将抛出ClosedByInterruptException,它是IOException的一个实例
下面是如何“可中断地”从TCP服务器读取字节
SocketChannel ch = SocketChannel.open();
ch.connect(new InetSocketAddress("host", 80));
ByteBuffer buf = ByteBuffer.allocate(1024);
int n = ch.read(buf);