I was just trying to create a Thread in a static
block in Java that caused a deadlock to occur. The code snippet is as follows.
package deadlock;
f
Technically, you don't call this a deadlock. "Deadlock" implies that there is a monitor contention of some sort.
What you are doing has the same effect as calling
synchronized (Main.class) {
try {
Main.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
as the first thing in your main method. You are in a wait state from which you are never woken up.
In order for the thread to be able to set the static value, the class must be loaded. In order for the class to be loaded, the thread must end (so that the static block completes). That's probably why you have a deadlock.
if you comment out
try
{
t.join();
}
catch (InterruptedException e)
{
System.out.println(e.getMessage());
}
deadlock will not occur...Your thread will run after class load.