I have recently started with multi-threading in Java
I have an issue solving a problem where I have got only 5 Threads ranging from T1, T2,...T5.
The task is to print numbers from 1 to 10 in the following order.
T1 -> 1
T2 -> 2
T3 -> 3
T4 -> 4
T5 -> 5
T1 -> 6
T2 -> 7
T3 -> 8
T4 -> 9
T5 -> 10
I tried solving it with this piece of code.
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread[] tArray = new Thread[] { new Thread(counter, "T1"), new Thread(counter, "T2"),
new Thread(counter, "T3"), new Thread(counter, "T4"), new Thread(counter, "T5") };
for (int i = 0; i < 10; i++) {
if (i < 5) {
tArray[i].start();
tArray[i].join();
} else {
tArray[i - 5] = new Thread(counter, "T" + ((i - 5) + 1)); //Instantiating new Thread which is not allowed.
tArray[i - 5].start();
tArray[i - 5].join();
}
}
}
public class Counter implements Runnable {
private int count = 0;
@Override
public synchronized void run() {
System.out.println(Thread.currentThread().getName() + " -> " + ++count);
}
}
But since only 5 threads are allowed my solution is not accepted since I am also instantiating new Thread
in the else
block of the for
loop.
Any help would be highly appreciated.
It can be changed using the method setPriority() of class Thread. There are three static variables for thread priority in Java i.e. MIN_PRIORITY, MAX_PRIORITY and NORM_PRIORITY. The values of these variables are 1, 10 and 5 respectively.
You can add 'n' number of Threads to print the alternate series. i.e Using 3 thread at once. You can also print the series with more than Difference of more than 1. i.e 1,3,5 etc.
You need to arrange interaction between threads. The most natural way for thread interaction is setting up blocking queues which connect threads. Queues can be independent objects, or belong to particular threads. In your case, you need to make a circle of 5 threads.
class CountPrinter extends Thread {
String name;
ArrayBlockingQueue<Integer> inp = new ArrayBlockingQueue<>();
CountPrinter next;
public void run() {
for (;;)
int n = inp.take();
if (n == 11) {// only 10 numbers must be printed
next.inp.put(11);
return;
}
System.out.println(name+"->"+n);
next.inp.put(n+1);
}
}
}
After creating a thread and before its start, you need to assign the fields name
and next
. I believe you can program this yourself.
Also, the first thread must be provided with the initial value 1
.
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