as you have declared "num" as static , by the time Thread "t1" completed it's execution in synchronized block value of "num" becomes 10 which is shared by thread "t2" also. When t2 enters the synchronized block after t1 released, the value of "num" is 10. So t2 does not enter into the while loop as the condition is failed.
Actually the statement "synchronized(this)" has no effect on the order of excecution of the threads. You are synchronizing on the "this" object. So for thread t1, the object is t1 and for thread t2, it is t2. As such there is no chance of there being a contention between t1 and t2.
As to the output when num is static, it looks like thread t1 is completing its run() method before t2. So when t2 begins it run() method, num is 9 and hence it won't produce any output. But as said earlier this is not due to t2 blocking because it can't get a lock (Each thread is having a lock on its own instance).
To better understand the flow, "slow" down the excecution by putting the threads to sleep for a while. Also, output the thread name along with num value, to see which thread is producing the output. Then you will see that both the threads are running.
When num was static in your program, I was able to get the following output while debugging
0 0 2 3 3 4 5 7 8 9
Really there is no way to explain this than debugging or sleep in Windows platform.
In the following program it is guranteed that the output will be as follows.
0 1 2 3 4 5 6 7 8 9
because mutex is shared between the two threads.
Joined: Oct 12, 2004
So, my question is, what is the effect of making a variable static on threads?
When you created Multiple with static num and t1 and t2 as two instances of Multiple, this is what happened.
Object t1 and t2 of type Multiple shares the same memmory location for 'num'. That means if t1 changes the value of num, the change affects num in t2 too. if t1 changes value of num from 0 to 1, the value of num in t2 is 1 now. if t2 changes value of num from 1 to 2, the value of num in t1 is 2 now. and so on.
When num was not static t1 had a variable called num exclusively for t1 while t2 had a variable called num. t1.num and t2.num were two different memmory locations. That means if t1 changes the value of num, the change doesn't affect num in t2. Intially both t1.num and t2.num were 0. if t1 changes value of num from 0 to 1, the value of num in t2 is still 0. if t2 changes value of num from 0 to 1, the value of num in t1 is still 1(current value of t1). and so on.
Irrespective of wether you are implementing threads or not ,u need to understand that static variables are class members and not instance,so in ur code ur making two instances of Class so each gets a member num whose initila value is 0.so u get the first output...but when u make static it is class variable and the single varibale is shared by both the instances.....the first instance has incremented num to 9 and the second instance gets the num as 9...