in the above code, why the output is mix-up of all the objects created i.e. why the output is not synchronized( means t1 should print all its values first, then t2 the t3 the t4).
nothing is different when is remove the synchronized keyword ...
But when make the prinTable() as static then only it is printing in a synchronized behavior ?
hello A.J. Côté
I read thread provided by you, but didn't understood , because right now I have not reached the wait() notify() topics. I read this code(my question) in the static Synchronization topic . so the thread provided by you is not helpful to me
Jeanne Boyarsky wrote:Each thread has a different instance of the Table object. Therefore they are synchronizing on different objects and never wait for each other.
Thumbs up! making the printTable() method static makes all threads synchronize on the common Class monitor instead of each instance monitor.
Also, I see no guarantee that thread 1 is actually going to start printing before thread 2 etc... Threads might theoretically print out of order I think...
In short Jeanne was right and I explained it further:
static printTable() works because you synchronize on the unique Class monitor.
printTable() does not work because you synchronize on 3 different instance monitors.
even with static, there is still a possibility that the threads will print out of order but with static at least the printout will be grouped with regards to each thread..
To guarantee the right order, you could use thread.join() then you wouldn't need to synchronize at all.
You can also use wait() and notify to guarantee the thread order. You need to use wait() and notify() if you want to loop forever with each thread executing in order, Thread.join() wouldn't work in this case.
Note that there are other layers of abstraction on top of wait() and notify()