Question : There are three threads, which can print an assigned array as below:
Thread1 - {1,4,5}
Thread2 - {2,5,7}
Thread3 - {3,6,9}
Write a program that print the output so that the output is always 1,2,3,4,5,6,7,8,9? Also, make it extendible so that the same logic can be applied to more number of threads.
Solution:
Thread1 - {1,4,5}
Thread2 - {2,5,7}
Thread3 - {3,6,9}
Write a program that print the output so that the output is always 1,2,3,4,5,6,7,8,9? Also, make it extendible so that the same logic can be applied to more number of threads.
Solution:
public class MultipleThreads { public static void main(String args[]) { //same instance of printer that is shared among the threads Printer printer = new Printer(3); // three is the maximum number of threads. NumberThread thread1 = new NumberThread(new Integer[]{1,4,7}, 1, printer); // First arguement is the array, second is the Thread number, printer is the shared instance NumberThread thread2 = new NumberThread(new Integer[]{2,5,8}, 2, printer); NumberThread thread3 = new NumberThread(new Integer[]{3,6,9}, 3, printer); thread1.start(); thread2.start(); thread3.start(); } }The NumberThread class looks like:
public class NumberThread extends Thread { private Integer[] integerArray; private int threadNumber; private Printer printer; //Constructor public NumberThread(Integer[] array, int thread, Printer printer) { this.integerArray = array; this.threadNumber = thread; this.printer = printer; } @Override public void run() { int index = 0; // index to keep track that all the elements are traversed while(index < integerArray.length) { synchronized(printer) { while(!printer.myTurn(this.threadNumber)) { try { printer.wait(); } catch (InterruptedException ie) { } } printer.print(integerArray[index]); index++; printer.notifyAll(); } } } }The Printer class is as follows:
public class Printer { private int maxThreads; private int currentThread = 1; public Printer(int numberOfThreads) { this.maxThreads = numberOfThreads; } public void print(int number) { // print the number System.out.println(number); currentThread = (currentThread % maxThreads) + 1; } public boolean myTurn(int threadNumber) { return currentThread == threadNumber; } }
In order to extend the above logic, it can be extended for the number of elements in array and the number of threads that needs to be executed in a one-one-by kind of execution.
Please leave a comment if you think there is a problem in the above code or if there is any modification / optimization that can be done.
Please leave a comment if you think there is a problem in the above code or if there is any modification / optimization that can be done.