When i ran the following program it just hung forever and seems to me it is because of deadlock.
From my understanding I
- The static field
isInitialized
is initially set tofalse
. - Then the main thread creates a background thread whose run method
sets
isInitialized
totrue
. - The main thread starts the background thread and waits for it to
complete by calling
join
. - Once the background thread has completed, there can be no doubt that
isInitialized
must ha been set to True.
But when i ran the program, found that it prints nothing; it just hangs!
public class Test {
private static boolean isInitialized = false;
static {
Thread t = new Thread(new Runnable() {
public void run() {
isInitialized = true;
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
}
}
public static void main(String[] args) {
System.out.println(isInitialized);
}
}
Can some one help me understand this behavior,Is there any deadlock if so why ?