【发布时间】:2020-09-11 18:54:24
【问题描述】:
public class MyVisibility {
private static int count = 0;
private static Object lock = new Object();
public static void main(String[] args) {
new MyVisibility.thread1().start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
return;
}
new MyVisibility.thread2().start();
}
static class thread1 extends Thread {
int i = 0;
@Override
public void run() {
super.run();
while (true) {
synchronized (lock) {
count++;
System.out.println("Thread one count is " + count);
try {
lock.wait();
System.out.println("i am notified");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (count > 5) {
return;
}
}
}
}
static class thread2 extends Thread {
int i = 10;
@Override
public void run() {
super.run();
while (true) {
synchronized (lock) {
count++;
System.out.println("Thead 2 count is " + count);
lock.notify();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (count > 10) {
return;
}
}
}
}
}
在上面的代码中, 当前执行结果:我可以看到 lock.notify() 仅在 while 循环结束后才被调用。
我的假设是因为 lock.notify() 在 count 变量增加后立即被调用,并且它应该立即通知等待线程恢复其执行,而不是在第二个线程完成执行调用之后等待线程恢复,这是什么原因,有人可以纠正我的理解有什么问题吗。
谢谢。
【问题讨论】:
-
请显示您的预期和实际输出。
-
提示:在
synchronized块或synchronized方法中调用sleep(...)实际上总是一个坏主意。 -
@SolomonSlow 是的,我知道,如果您在第一个线程上看到我没有使用睡眠,我正在尝试一些东西,并且在此处放置时没有删除第二个线程中的代码..跨度>
标签: java multithreading thread-safety wait notify