In: Computer Science
Write a program (in C, or Java, or C++, or C#) that creates
three new threads (besides the already existing main thread) and
synchronizes them in such a way that each thread displays it's
thread id in turn for 5 iterations. The output of the program
should look like this:
Thread 1 - iteration no. 1
Thread 2 - iteration no. 1
Thread 3 - iteration no. 1
Thread 1 - iteration no. 2
Thread 2 - iteration no. 2
Thread 3 - iteration no. 2
Thread 1 - iteration no. 3
Thread 2 - iteration no. 3
Thread 3 - iteration no. 3
Thread 1 - iteration no. 4
Thread 2 - iteration no. 4
Thread 3 - iteration no. 4
Thread 1 - iteration no. 5
Thread 2 - iteration no. 5
Thread 3 - iteration no. 5
PLEASE GIVE IT A THUMBS UP, I SERIOUSLY NEED ONE, IF YOU NEED ANY MODIFICATION THEN LET ME KNOW, I WILL DO IT FOR YOU
class SynchronizeThreads {
private static int thread_num = 1;
private static int iter_num = 1;
public static void main(String[] args) throws InterruptedException {
Thread[] pthreads = new Thread[3];
for (int thread_index = 0; thread_index < pthreads.length; thread_index++) {
int threadId = thread_index + 1;
pthreads[thread_index] =
new Thread(
new Runnable() {
@Override
public void run() {
while (true) {
synchronized (this) {
if (thread_num == threadId && iter_num <= 5) {
System.out.println(
"Thread " + thread_num + " - iteration no. " + iter_num
);
System.out.println("");
thread_num++;
if (threadId == pthreads.length) {
iter_num++;
thread_num = 1;
}
}
if (iter_num == 6) {
break;
}
}
}
}
}
);
pthreads[thread_index].start();
}
for (int thread_index = 0; thread_index < pthreads.length; thread_index++) {
pthreads[thread_index].join();
}
}
}