我正在研究数据包嗅探器,但是我遇到了阻止包含阻塞方法的线程(没有弃用方法)的方法。
有关的方法是来自pcap4j库的loop()
。由于它是一种阻塞方法,我将它放入一个线程中以保持主要的工作。但是,为了将过滤器应用于pcap接口,我必须打破循环并重新启动它,因为库的breakloop()
函数返回InterruptedException
。所以我的想法是杀死包含该方法的线程。但由于我无法进入库循环导致方法被阻塞,我无法通过检查线程是否被中断来实现。
Thread t = new Thread(new Runnable() {
@Override
public void run() {
loop(args);
}
});
t.start();
我怎么能阻止它?
编辑:我做的是从源代码重新编译库,从PcapHandle类中删除InterruptedException。
使用Thread#getAllStackTraces,您可以获得所有线程。 SO Has a few other answers to this以及获得线程。找到线程后,您可以中断它。 Thread.class
还有一些其他标识符也可以帮助找到线程。
编辑:你使用kaitoy / pcap4j?如果是这样的话breakLoop()关于InterruptedException
什么都做不了,那就是图书馆打算如何打破它。如果他们需要实现一个功能,我会考虑将问题放在他们的github上。
import java.util.Set;
class TestStuff {
public static void main(String[] args) {
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for (Thread thread : threadSet) {
if(thread.getName().equals("some-name")){
thread.interrupt();
}
}
}
}