The code is below, in the Main
method I call a static method:
public class Main {
public static void main(String[] args) {
MyFactory.getSomething();
System.out.println("over");
}
}
In the static method, let the main thread wait, then by demo-thread wake up. But the main thread does not wake up and I don't know why.
import java.util.concurrent.TimeUnit;
public class MyFactory {
private static Object lock = new Object();
static{
init();
}
private static void init(){
new Thread(()->{
try {
// make this thread run after main thread
TimeUnit.SECONDS.sleep(3);
System.out.println("task run...");
synchronized (lock){
lock.notifyAll(); // notify main thread
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
},"demo-thread").start();
synchronized (lock){
try {
System.out.println("waiting...");
lock.wait(); // wait
System.out.println("wake up");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public static Object getSomething(){
return null;
}
}
The output is below:
waiting...
My expected should be like this:
waiting...
task run...
wake up
over
Here is the demo code on Github You can download it to run.
My try:
I see losts of people say may be a dead lock cause the problem.I don't think so.Because we don't see task run...
info in the output. So the demo thread
not aquire the lock at all.
When I change the code In MyFactory.java
.(Add a new thread to run init method)
from this
static{
init();
}
to this.
static{
new Thread(()->init()).start();
}
Every thing work fine.The program not block.
Here is the out put after I change the code .
over
waiting...
task run...
wake up
Back to the original question "Why main thread not wake up"? I think the JVM didn't load the
MyFactory.class
completely due to main thread blocking。I don't know if my guess is right???