As part of some interview questions, I found the following question.
You are given a paragraph that contains n number of words, you are given m threads. What needs to be done, each thread should print one word and give control to the next thread, so each thread will continue to print one word, in case the last thread arrives, it should call the first thread. Printing will be repeated until all words are printed in the paragraph. Finally, all threads should exit gracefully. What synchronization will be used?
As the problem checks how we can coordinate threads and shared variables, I look at numbers instead of words.
My approach: I will have N lock objects for N threads. Each thread will be provided with a lock object and a lock object of the next thread. I will first lock my lock object, and then on this monitor I will lock the next thread lock object again, then notify it, and then wait for my own lock.
Here is the code
public class PrintNThreads { public static void main(String[] args) { int n = 10; if(n < 2) return; Object[] lockObjects = new Object[n]; for(int i=0;i<n;i++) { lockObjects[i] = new Object(); } for(int i=0;i<n;i++) { new NumberThread("Thread-"+(i+1), lockObjects[i], lockObjects[(i+1)%n]).start(); } } } class NumberThread extends Thread { static volatile int i = 0; static void printIncrement(String threadName) { System.out.println(threadName+" "+(++i)); } Object thisLock; Object nextLock; final String threadName; public NumberThread(String threadName,Object thisLock, Object nextLock) { this.nextLock = nextLock; this.thisLock = thisLock; this.threadName = threadName; } public void run() { while(true) { synchronized (thisLock) { synchronized (nextLock) { nextLock.notify(); printIncrement(threadName); } try { thisLock.wait(); } catch (InterruptedException e) {
I see the result sequentially in sequence and in stream order.
Output: Thread-1 1 Thread-2 2 Thread-3 3 Thread-4 4 Thread-5 5 Thread-6 6 Thread-7 7 Thread-8 8 Thread-9 9 Thread-10 10 Thread-1 11 Thread-2 12 Thread-3 13 Thread-4 14 Thread-5 15 Thread-6 16 Thread-7 17 Thread-8 18 Thread-9 19 Thread-10 20
Read my code and let me know your suggestions. We cannot exit if there are multiple threads.
source share