Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a specific thread to be the next one to enter a synchronized block?

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?

like image 270
Vinoth Kumar C M Avatar asked Jul 04 '11 16:07

Vinoth Kumar C M


People also ask

How can we make threads to run one after another in sequence?

By using join you can ensure running of a thread one after another.

How will restrict a block of code only for certain number of threads?

Use a semaphore with three permits: Semaphores are often used to restrict the number of threads that can access some (physical or logical) resource.

Can two threads access a synchronized method at the same time?

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.


1 Answers

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();}
}
like image 133
M Platvoet Avatar answered Oct 19 '22 23:10

M Platvoet