使用JNA本机等待调用检测线程中断(Windows) [英] Detecting thread interruption with JNA native wait call (Windows)
问题描述
我正在尝试编写一些通过JNA执行等待的代码(例如通过调用Kernel32函数WaitForSingleObject),但是如果调用Thread.interrupt(),我也希望等待完成;我假设Java使用类似Event对象的东西来实现中断;有没有办法从Java获取事件,以便在调用WaitForMultipleObjects时使用它?或者,如果线程被中断,我还有其他任何方式可以安排等待吗?
I'm trying to write some code that performs a wait via JNA (e.g. by calling the Kernel32 function WaitForSingleObject), but I'd also like the wait to finish if Thread.interrupt() is called; I assume Java uses something like an Event object to implement interruption; is there any way of getting the Event from Java in order to use it in a call to WaitForMultipleObjects? Or is there any other way I could arrange for my wait to finish if the thread is interrupted?
推荐答案
Java通过NIO支持它并且很少有人知道,这个类是抽象的但是没有问题:
Java supports it via NIO and very few people are aware of, the class in question is abstract but that's no issue:
java.nio.channels.spi.AbstractInterruptibleChannel
。它有3种感兴趣的方法: begin()
和 end()
,这些是最终的,加上你有的那个实现:protected abstract void implCloseChannel()throws IOException
该方法将从线程调用interrupt()调用,所以要小心。
java.nio.channels.spi.AbstractInterruptibleChannel
. It has 3 methods of interest: begin()
and end()
, those are final, plus that one you have to implement: "protected abstract void implCloseChannel() throws IOException"
The method is going to be called from the thread invoking interrupt(), so be careful.
使用非常简单:在输入本机代码之前调用begin,返回时调用end()。处理implCloseChannel中断。
The use is very simple: call begin before entering the native code and end() upon return. Handling the interruption in implCloseChannel.
快乐编码!
这篇关于使用JNA本机等待调用检测线程中断(Windows)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!