When we actually need to use the wait, notify
and notifyAll
methods, isn't the synchronized
keyword is enough to synchronize threads
.
Asked
Active
Viewed 129 times
-1

Yagami Light
- 1,756
- 4
- 19
- 39

Kiran Kumar
- 1,033
- 7
- 20
-
1That depends on how you define "synchronize threads". If it is just to prevent concurrent access to some piece of code then `synchronized` is probably sufficient, if the threads need to interoperate (e.g. producer-consumer) it might not (the consumer might want to wait until it gets notified of new messages/elements/whatever by the procuder). – Thomas Aug 10 '16 at 14:40
-
You mainly need those when you wish your threads to **communicate** with each other; like some waiting until another one is done ... and those methods allow you to handle that in an efficient way. – GhostCat Aug 10 '16 at 14:42
-
@SotiriosDelimanolis, IMO the question to which you linked is a very weak example of how wait() and notify() should be used. See the Oracle 'guarded blocks' tutorial. https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html – Solomon Slow Aug 10 '16 at 15:03
-
@jameslarge Let's find a better one. – Sotirios Delimanolis Aug 10 '16 at 15:05
-
@KiranKumar, you can see the true purpose of wait()/notify() if you read the tutorial that I linked to in my previous comment. In a nutshell: You use wait() and notify() whenever you need one or more threads to wait until some other thread makes some condition become true (e.g., to wait until a queue becomes not-empty). – Solomon Slow Aug 10 '16 at 15:05
-
@SotiriosDelimanolis, I tried. I couldn't find any that come right to the point, but the new "Documentation" project had nothing to say about wait()/notify() either, so I started a new topic there http://stackoverflow.com/documentation/java/5409/wait-notify#t=201608111547289865395 – Solomon Slow Aug 11 '16 at 15:49
1 Answers
1
First of all, Why use Synchronization?
The synchronization is mainly used-
To prevent thread interference.
To prevent consistency problem.
What are the types of Synchronization?
There are two types of synchronization
Process Synchronization
Thread Synchronization
In case of Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread communication.
Mutual Exclusive
Synchronized method.
Synchronized block.
static synchronization.
Cooperation (Inter-thread communication in java)
If you understand all these, its the answer to your question.
It depends on how and in what purpose you are using Synchronization
.

Sirsendu
- 283
- 1
- 8
-
Yes, you are right, I got the answer what I want, I knew it, but some how I couldn't think of those scenario. Thank you. – Kiran Kumar Aug 10 '16 at 14:49