Threading and synchronization issues
java, multithreading
Solution
It is perfectly possible for `thr1` to start and be parked before it hits `synchronized` - then `thr2` gets the lock and exits.
My only concern is how `(int) (Math.random() * 30)` can evaluate to `19`. Now that is weird.
Problem
In some cases the following program actually stops (because of Thread 2), when it shouldn't. Why is that happening? Thread 1: Basically locks `global` and does a while loop. Thread 2: Attempts to get a lock on `global` and it it succeeds, proceeds to stop the program. BUT~ Thread 1 is started first, so technically Thread 2 should never get called and hence the program should never quit. ``` static Integer global = 30; public static synchronized void setVar(int x, String from) { System.out.println(global + " " + x + " - " + from); global = x; } public static void main(String [] args) { Thread thr1 = new Thread(new Runnable() { @Override public void run() { synchronized(global) { while(true) { setVar((int) (Math.random() * 30), "Thread 1"); } } } }); Thread thr2 = new Thread(new Runnable() { @Override public void run() { synchronized(global) { setVar((int) (Math.random() * 30), "Thread 2"); System.exit(0); } } }); thr1.start(); thr2.start(); } ``` Output (That I get once in a while) 30 19 - Thread 2