Why is thread synchronization used in java when we can achieve the same result by setting different priorities to the threads? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why is thread synchronization used in java when we can achieve the same result by setting different priorities to the threads?

What exactly is thread synchronization?

19th Aug 2020, 2:52 PM
Rashmi
Rashmi - avatar
2 Answers
+ 5
setPriority working depends on internal OS. Sometimes it does not works, depends on it using internal os task scheduler. So it is not guaranteed it will work on priorites.. One more, I think, you can set priorities when you have less number of threads may less than 10.. But what if you have to deal with hundred threads? What if they have same priority? And you can set priorities on threads only but you can apply synchronisation on blocks, methods classes as well. Actually, may I missing more points.. But this is points currently I got.. Hope it make sense.. Hope it helps.. Thread synchronisation means "if a thread is synchronised, then it will lock it resources it using, no other thread can take that resources that got locked by synchronised thread. Edit: Rashmi I found this, may clear your doubt fully. Take a look.. https://www.quora.com/What-is-the-use-of-synchronization-in-Java-if-we-have-priority-methods-which-can-also-give-consistent-output-to-set-priority-for-threads
19th Aug 2020, 3:57 PM
Jayakrishna 🇮🇳
+ 1
Thread synchronization is necessary when more than 1 thread at a time is trying to modify the state of an object. You generally use wait() method which in turn releases the lock on the object unlike sleep() which doesn't. And then the notify() method helps the thread in waiting state to again move to running state. Just like rightly said by Jayakrishna🇮🇳 you cannot depend on the the setPriority() because on a system level it is the OS scheduler which will specify the time of execution of a particular thread depending on the algorithm used like FCFS or SJF or Round Robin etc. https://www.sololearn.com/discuss/33435/?ref=app
19th Aug 2020, 9:18 PM
Avinesh
Avinesh - avatar