Write a Java program to create two threads, which alternately displays numbers from 1 to 10. Each thread sleeps for 1 second before displaying next number.
class One extends Thread {
public void run() {
for(int i=1; i<=10; i++) {
System.out.println("One : "+i);
try {
Thread.sleep(1000);
}
catch (InterruptedException ie) { }
}
}
}
class Two extends Thread {
public void run() {
for(int i=1; i<=10; i++) {
System.out.println("Two : "+i);
try {
Thread.sleep(1000);
}
catch (InterruptedException ie) { }
}
}
}
public class AlternateTwoThreads {
public static void main(String[] args) {
One t1 = new One();
Two t2 = new Two();
t1.start();
t2.start();
}
}
One : 1
Two : 1
Two : 2
One : 2
One : 3
Two : 3
One : 4
Two : 4
One : 5
Two : 5
One : 6
Two : 6
One : 7
Two : 7
One : 8
Two : 8
One : 9
Two : 9
One : 10
Two : 10