我有以下代码块:
public void startListening() throws Exception {
serverSocket = new DatagramSocket(port);
new Thread() {
@Override
public void run() {
System.out.print("Started Listening");
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
while (!stopFlag) {
try {
serverSocket.receive(receivePacket);
String message = new String(receivePacket.getData());
System.out.println("RECEIVED: " + message);
} catch (Exception ex) {
System.out.print("Execption :" + ex.getMessage());
}
}
}
}.start();
}
public void stopListening() {
this.stopFlag = true;
}
假设我将 stopFlag 设置为 true。serverSocket.receive(receivePacket);
将等到它收到一个数据包。如果我希望线程在 stopFlag 设置为 true 后立即退出,我应该怎么做。