0

How can we ensure sequencing among 3 or more threads in Java using wait, notify (preferably) or other high level constructs.

For example, for 3 threads, T1, T2 & T3 which prints 1,4,7... 2,5,8... 3,6,9... respectively should execute in order T1 > T2 > T3 > T1 > T2 > T3 > T1 and so on... Final output looks like below:

T1 1

T2 2

T3 3

T1 4

T2 5

T3 6

T1 7

.

.

.

Please note no. of threads is taken as input from user and is not hard coded.

I understand there is no point in using multiple threads if they are to run in sequence, but this is a practice problem.

Please help possibly with a code snippet.

saharsh-jain
  • 486
  • 7
  • 11

1 Answers1

0

If you have n threads, create an array of n binary semaphores (also known as locks or non-recursive mutexes). Semaphore [] locks = new Semaphore [n]; Before launching the threads, initialize all the locks to 0. Every thread routine should get its number so that thread 0 will have a local variable indicating that it is thread 0. Now every thread routine should start with locks[¡].lock(); and end with locks[(i+1)%n].unlock();

Then launch all the threads. And call locks[0].unlock()

The general idea or recipe here is thread synchronization. You start with locks initialized to lock, and then unlock them in the order you want to create a sequence. That's in contrast to thread protection where you typically start with locks in an unlocked state, and lock them when you are in a critical section.

Back to your problem, if you want the threads to go round and round. You can do this: (java)

void run()
{
    while(isRunning)
    {
        lock[i].lock();
        ////Your task
        lock[(i+1)%n].unlock();
     }
 }

So for example thread 0 will get to the lock section and block until the main thread finished launching all the threads, and when the main thread calls locks[0].unlock(), thread 0 will perform the task, unlock thread and go back an get locked on lock[0] because it did not unlock it, thread 0 will wait for the last thread which will unlock it in the end of its routine.

EDIT:

You can have a similar solution with one mutex and n conditional variables, but the idea is the same.

Michael P
  • 2,017
  • 3
  • 25
  • 33
  • 2
    You have mention "when the main thread calls locks[0].unlock(), thread 0 will perform the task, **unlock thread** and go back" How will a thread unlock the lock which was previously locked by main thread? I believe it's not doable with Mutex because only same thread can lock and unlock a Mutex. – saharsh-jain Aug 09 '15 at 03:06
  • @SaharshJ, you are right. Most mutexes are recursive, and are owned by the thread that locked it. Here I used the "Mutex" as a binary semaphore, see this answer http://stackoverflow.com/a/189778/2777540 . I believe both pthreads and Java Mutexes are indeed recursive. Let me edit the answer to avoid confusion, and thank you for the remark – Michael P Aug 09 '15 at 04:25