Given the number 1, 2, 3, 4, 5, 6 , 7, 8, 9, 10, 11, 12 I have Three threads, say Thread-1(print 1), Thread-2(print 2) and Thread-3(print 3) and then again hread-1(print 4), Thread-2(print 5) and Thread-3(print 6) and so on.. How I can call them in loop such that they will execute alternatively, Output(Expected)--- 1 2 3 4 5 6 7 8 9 10 11 12 However my below code is only printing 1 2 3
public class RunAlternateThread {
public static void main(String[] args) throws InterruptedException {
PrintNum count = new PrintNum();
Thread t1 = new Thread(new Thread1(count));
//t1.setPriority(5);
Thread t2 = new Thread(new Thread2(count));
//t2.setPriority(7);
Thread t3 = new Thread(new Thread3(count));
//t3.setPriority(9);
t1.start();
t2.start();
t3.start();
}
}
class Thread1 implements Runnable {
PrintNum count = null;
Thread1(PrintNum count) {
this.count = count;
}
public void run() {
synchronized (count) {
count.print1();
//count.wait();
count.notifyAll();
try {
count.wait(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} }
}
}
class Thread2 implements Runnable {
PrintNum count = null;
Thread2(PrintNum count) {
this.count = count;
}
public void run() {
synchronized (count) {
count.print2();
count.notifyAll();
try {
count.wait(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
class Thread3 implements Runnable {
PrintNum count = null;
Thread3(PrintNum count) {
this.count = count;
}
public void run() {
synchronized (count) {
count.print3();
count.notifyAll();
try {
count.wait(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
class PrintNum {
static int num = 1;
void print1() {
if(num == 12) {
try {
Thread.sleep(10000);
}
catch (Exception e){
}
}
System.out.println(this.num);
num++;
}
void print2() {
if(num == 12) {
try {
Thread.sleep(10000);
}
catch (Exception e){
}
}
System.out.println(this.num);
num++;
}
void print3() {
if(num == 12) {
try {
Thread.sleep(10000);
}
catch (Exception e){
}
}
System.out.println(this.num);
num++;
}
}
This does what you are asking and i left the thread numbers so you can test it