[英]How can I stop thread containing blocking operation?
I'm working on a packet sniffer but I'm getting trouble about the way to stop a thread (without deprecated methods) containing a blocking method. 我正在研究数据包嗅探器,但是在停止包含阻塞方法的线程(无不推荐使用的方法)方面遇到麻烦。
The concerned method is the loop()
one from pcap4j library. 有关的方法是pcap4j库中的
loop()
。 As it is a blocking method, I put it into a thread to keep the main one working. 因为它是一种阻塞方法,所以我将其放入线程中以保持主线程正常工作。 However, in order to apply a filter to the pcap interface, I have to break the loop and restart it as the
breakloop()
function of the library returns an InterruptedException
. 但是,为了将过滤器应用于pcap接口,我必须中断循环并重新启动它,因为库的
breakloop()
函数返回了InterruptedException
。 So my idea was to kill the thread containing the method. 所以我的想法是杀死包含该方法的线程。 But as I can't get into the library's loop causing the method to block, I'm unable to do it by checking whether the thread is interrupted or not.
但是由于无法进入导致该方法阻塞的库循环,因此无法通过检查线程是否中断来做到这一点。
Thread t = new Thread(new Runnable() {
@Override
public void run() {
loop(args);
}
});
t.start();
How can I stop it ? 我该如何阻止它?
EDIT : What I did was to recompile the library from its source, removing the InterruptedException from the PcapHandle class. 编辑 :我所做的是从其源代码重新编译该库,从PcapHandle类中删除了InterruptedException。
Using the Thread#getAllStackTraces you can obtain all the threads. 使用Thread#getAllStackTraces可以获得所有线程。 SO Has a few other answers to this as well for getting a hold of the threads.
因此 ,对于保持线程,还有其他一些答案 。 After finding the thread you can interrupt it.
找到线程后,您可以中断它。 The
Thread.class
also has some other identifiers that may help find the thread too. Thread.class
还具有其他一些标识符,这些标识符也可能有助于查找线程。
Edit: Are you using kaitoy/pcap4j ? 编辑:您正在使用kaitoy / pcap4j吗? if so breakLoop() Nothing can be done about the
InterruptedException
, thats how the library intended for it to be broken. 如果是这样,则BreakLoop()关于
InterruptedException
不能做任何事情,那就是库打算如何破坏它。 I would look at putting an issue in with their github if they need to implement a feature. 如果他们需要实现功能,我会考虑在他们的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();
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.