Here is a similar question: when static class initialization. And based on JLS 12.4.1, A class static variable will be initialized after one of these following events happen:
- an instance of the class is created
- a static method of the class is invoked
- a static field of the class is assigned,
- a non-constant static field is used, or
- for a top-level class, an assert statement lexically nested within the class is executed.
So in your case, I guess you need assure your global time variable is assigned before enter that while loop by a simple assignment, like
public class Global {
public static int time;
}
public class MultipleSleepingBarber implements Runnable {
public void run() {
Global.time = Global.time + 1;
System.out.println("Time is " + Global.time);
}
public static void main(String args[]) {
Global.time = 0;
for (int i = 0; i < 10; i++)
(new Thread(new MultipleSleepingBarber())).start();
}
}