Why is the output not synchronized, how to make it run synchronized?
The output is synchronized. Each line is complete and correct. If it were not synchronized, you would see some lines inside another line.
I assume you mean;
how can I hold a lock for the whole loop?
Outside the loop you add
synchronized(sharedObject) {
and
}
at the end.
What are other methods, i know few Locks and wait/notify?
I highly recommended you read the book Java Concurrency in Practice. It is an excellent book, possibly the best written for Java.
Which one and how exactly they help in synchronization?
They have a number features which are interrelated
- the obtain exclusive access to a resource using a combination of compare-and-set, possibly some state such as a queue of waiting threads, a call to the OS if there is a long delay.
- a read/write memory barrier so that you get a consistent view of anything read/written in a similar block of code.
- unlocking usually has checks that this is being called correctly.
- some lock also can be monitored so you can see deadlocks, and waiting locks.