为什么在指定了 wait 的情况下,lock wait 下面的行会被执行?
Why does the line below the lock wait get executed though wait has been specified?
我编写了以下代码,其中启动方法应该等到停止方法通知它。但是在执行期间,尽管我已指定它等待,但启动方法下方的日志行会被打印出来。下图是我的启动方法实现如下
private static boolean stopThread = false;
public static void start(String[] args) {
startThread();
synchronized (serviceThread) {
try {
while(stopThread) {
serviceThread.wait();
}
LOGGER.log(Level.INFO, "Thread: Just after wait method");
} catch (InterruptedException e) {
LOGGER.log(Level.INFO, "'Wait' interrupted: " + e.getMessage());
}
}
}
下图是我的停止方法实现。
public static void stop(String[] args) {
if (serviceThread != null) {
LOGGER.log(Level.INFO, "Stopping the thread");
serviceThread.interrupt();
LOGGER.log(Level.INFO, "Thread: Successfully interrupted");
synchronized (serviceThread) {
LOGGER.log(Level.INFO, "About to notify");
serviceThread.notify();
stopThread = true;
}
stopPlugins();
kubeLogManager.closeLogger();
messageBus.terminateMessageBus();
System.exit(0);
} else {
LOGGER.log(Level.INFO, "No thread to interrupt");
}
}
为什么 wait 方法下面的日志行甚至在调用 stop 方法之前就被打印出来了?请指教
请参阅 Object.wait 的文档:
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait()
interrupts and spurious wakeups are possible, and this method should always be used in a loop:
synchronized (obj) {
while (<condition does not hold>)
obj.wait();
... // Perform action appropriate to condition
}
您应该使用变量来指示何时调用 stop()
,并在调用 notify()
之前设置它。此外,使用 notifyAll()
更安全,因为如果您以某种方式让另一个线程等待该对象,它仍然有效。
我编写了以下代码,其中启动方法应该等到停止方法通知它。但是在执行期间,尽管我已指定它等待,但启动方法下方的日志行会被打印出来。下图是我的启动方法实现如下
private static boolean stopThread = false;
public static void start(String[] args) {
startThread();
synchronized (serviceThread) {
try {
while(stopThread) {
serviceThread.wait();
}
LOGGER.log(Level.INFO, "Thread: Just after wait method");
} catch (InterruptedException e) {
LOGGER.log(Level.INFO, "'Wait' interrupted: " + e.getMessage());
}
}
}
下图是我的停止方法实现。
public static void stop(String[] args) {
if (serviceThread != null) {
LOGGER.log(Level.INFO, "Stopping the thread");
serviceThread.interrupt();
LOGGER.log(Level.INFO, "Thread: Successfully interrupted");
synchronized (serviceThread) {
LOGGER.log(Level.INFO, "About to notify");
serviceThread.notify();
stopThread = true;
}
stopPlugins();
kubeLogManager.closeLogger();
messageBus.terminateMessageBus();
System.exit(0);
} else {
LOGGER.log(Level.INFO, "No thread to interrupt");
}
}
为什么 wait 方法下面的日志行甚至在调用 stop 方法之前就被打印出来了?请指教
请参阅 Object.wait 的文档:
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#wait()
interrupts and spurious wakeups are possible, and this method should always be used in a loop:
synchronized (obj) { while (<condition does not hold>) obj.wait(); ... // Perform action appropriate to condition }
您应该使用变量来指示何时调用 stop()
,并在调用 notify()
之前设置它。此外,使用 notifyAll()
更安全,因为如果您以某种方式让另一个线程等待该对象,它仍然有效。