I was asked this in an interview.
There are four threads t1,t2,t3 and t4. t1 is executing a synchronized block and the other threads are waiting for t1 to complete. What operation would you do, so that t3 executes after t1.
I answered that join method should do the trick, but it looks like it isn't the right answer.The reason he gave was, the join method and the setPriority method would not work on threads that are wait state.
Can we achieve this? If yes, how?
By using join you can ensure running of a thread one after another.
Use a semaphore with three permits: Semaphores are often used to restrict the number of threads that can access some (physical or logical) resource.
Two threads cannot access the same synchronized method on the same object instance. One will get the lock and the other will block until the first thread leaves the method. In your example, instance methods are synchronized on the object that contains them.
Every thread should simply wait() on a separate object. So t3 should wait on t3Mutex. You could then simply notify that specific thread.
final Object t1Mutex = new Object();
final Object t3Mutex = new Object();
...
synchronized(t3Mutex) {
//let thread3 sleep
while(condition) t3Mutex.wait();
}
...
synchronized(t1Mutex) {
//do work, thread1
synchronized(t3Mutex) {t3Mutex.notify();}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With