[英]Kill a Thread working with flag in Java
I implemented my own Thread in Java this way : 我以这种方式在Java中实现了自己的线程:
public class MyThread extends Thread{
protected boolean exit = false;
protected void kill(){
exit = true;
}
}
So when I create a thread, the method run() looks like : 因此,当我创建线程时,方法run()如下所示:
public void run() {
...
while(!exit) {
...
}
}
My question is the following : I'm using my thread class to receive and send datagrams. 我的问题如下:我正在使用线程类来接收和发送数据报。 But when the thread is waiting for a datagram, if I call the function MyThread.kill(), the thread will still wait a next packet before ending itself... How can I kill my thread without waiting for an another packet ?
但是,当线程正在等待数据报时,如果我调用函数MyThread.kill(),则该线程仍将等待下一个数据包,然后再结束自身... 如何在不等待另一个数据包的情况下杀死线程? Thank you very much
非常感谢你
After setting the exit flag, send the thread a datagram yourself to unblock it. 设置退出标志后,请自行向线程发送数据报以解除阻止。 By the way,
exit
should be volatile
. 顺便说一句,
exit
应该是volatile
。
The proper way to interrupt a call to DatagramSocket.receive()
is to close the socket, and receive()
will then throw a SocketException
. 中断对
DatagramSocket.receive()
的调用的正确方法是关闭套接字,然后receive()
将引发SocketException
。 So after setting the exit
flag, you should close the UDP socket in your kill()
method. 因此,在设置
exit
标志后,您应该在kill()
方法中关闭UDP套接字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.