I want to create three threads and print result of these threads alternately.
In this post,3 threads to print alternate values in sequence threads operates the same task. What i try to do is ,
//Thread Practice
//one number ,one char ,one string comining these two parallely
class Thread_1 extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getId() + "... " + i);
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
}
}
}
}
class Thread_2 extends Thread {
String s = new String("ABCDEFGHIJ");
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getId() + ".. " + s.charAt(i));
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
}
}
class Thread_3 extends Thread {
String s = new String("ABCDEFGHIJ");
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getId() + ".. " + i + s.charAt(i));
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
}
}
class Practice {
public static void main(String[] args) {
Thread_1 t1 = new Thread_1();
Thread_2 t2 = new Thread_2();
Thread_3 t3 = new Thread_3();
t1.start();
t2.start();
t3.start();
}
}
I want output to be 1 ,A, 1A then 2,B,2B and so on ,that is these threads should run alternately.With Sleep() ,the order is not guaranteed.
Can I achieve ordering over these threads to make them run alternately to get the desired output I want.(Purpose is learning insites of Threading).