我在while循环中有开关盒。而在一种情况下,其中有一个同步阻止,其后是break语句。该break语句导致循环中断而不是大小写中断。下面是代码。
while (!shutdown && !Thread.currentThread().isInterrupted()) {
try {
logger.info("Trying to Read message");
ServerResponseMessage response = gson.fromJson(jsonReader, ServerResponseMessage.class);
logger.info("Message Reading completed.");
if(response == null) {
logger.info("Received EOS Response, closing thread.");
break;
}
switch (response.getRequestType()) {
/* GET request type is considered as the request for the new object */
case GET:
object = response.getObject();
synchronized (requestLock) {
requestLock.notifyAll();
}
break;
/*
* If client receives HEARTBEAT message from Server, client need to response as
* Ack.
*/
case HEARTBEAT:
logger.info("Received Hearbeat");
ServerResponseMessage message = new ServerResponseMessage(RequestType.HEARTBEAT_ACK, null);
JsonWriter jsonWriter = new JsonWriter(new OutputStreamWriter(serverSocket.getOutputStream()));
jsonWriter.jsonValue(new Gson().toJson(message));
jsonWriter.flush();
logger.info("Sent Hearbeat Ack");
break;
default:
break;
}
logger.info("Completed reading.");
} catch (IOException e) {
logger.warn("Error while reading client", e);
shutdown = true;
}
}
在上面的代码中,GET情况导致循环中断,根据日志,它在notifyAll方法之后直接跳出while循环。请帮助。谢谢。
答案 0 :(得分:1)
为您的Switch
考虑一个标签,以便您可以在需要时轻松破坏该标签。
LOOP1:
while (condition) {
MY_LABEL:
switch (variable) {
case (a):
break LOOP1; // will break the loop -> Also continue; works as well.
break MY_LABEL; // it will break the switch and continue on loop
}
}
这通常对于嵌套循环很有用。有关更多信息,请参见the docs。