Threads aren't really syncronized... the code threads access are. Synchronization can come in many forms. Back to the Logger
example... Most classes I write have at least one constructor that takes a Logger
. Which gives the caller the ability to pass a Logger
to the object being instantiated so that it can share
it with other running objects. So all the classes running in a particular program can log to the same source.
This can present a small problem when dealing with threads. If four threads were all writing to the same logger at the same time, the output to the log would be hard to interpret at the least. One thread would interupt the next and what was streamed out to the console or file would be a garbled mess.
This is why there is synchronization. If the log
method is synchronized the the first thread that gets it, locks it and no other thread can use it untill that first thread releases that lock.
There are two ways to implement synchronization...