Hi, Please look at the code below and can you please suggest how can I synchronize in a way such that run method of one thread completes and only then the other thread is able to run.Such that the output is 123 ABC..........ABC... OR ABC.....ABC...ABC..123
No code needs to be synchronized in the code you have given. Since there is no single object which is being accessed from multiple threads, there is no need for a synchronization.
Any how, to get your problem statement to be solved, we can use join() method of Thread. Just use between and
The answer is - Every second all three listeners will report a new temperature. I did not understand that even if notifyAll(), only one thread will be getting the lock on the object and so every second one listener should report the temperature. Please clarify.
When notifyAll() is called, all the threads that wait on the forecaster object will be notified. So, all the threads will continue to execute the code after wait() (of course, only one thread will be getting the lock at a time). So every second 3 listeners will report the temperature.
Yeah, that is my doubt when only one thread will get the lock then how can all the three threads report the temperature, only one thread will enter the synchronized code block and should execute is 'nt it. So there should be only one System.out.println by any one of the threads. Please clarify my doubt. Thanks.
Please read the sequence carefully. When notifyAll() is called, all the three threads will be notified. All the 3 threads will come out of wait state. So, all of them will try to execute the synchronized method at the same time. But since the method is synchronized, only one thread will be able to execute it at a time. After one thread finishes the method and releases the lock, the second thread will start & the third thread will enter the method after 2nd thread finishes the method.
Please note:
When multiple threads are ready to execute a method which is synchronized, only one thread which gets the lock first will be able to enter the method and the other threads will wait for the currently holding thread to release the lock. The most important point here is the wait here does not require a notify() to be called.
Hope this helps.
What a show! What atmosphere! What fun! What a tiny ad!
a bit of art, as a gift, that will fit in a stocking