Write a thread that counts 1 to 10 and another thread that counts 1 to 10, one after another.
For eg: Thread1 Output: 1 Thread2 Output:1 Thread1 Output:2 Thread2 Output:2
I have written below code
public class Test1 extends Thread
{
public void run(){
for(int i=1;i<=10;i++){
//System.out.println(i);
try{
System.out.println(Thread.currentThread().getName()+"+i);
Thread.sleep(500);
}catch(Exception e){
System.out.println(e);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test1 t1=new Test1();
Test1 t2=new Test1();
//Test1 t3=new Test1();
t1.start();
t2.start();
//t3.start();
}
}
Got the output as:-
Thread-1 1
Thread-0 1
Thread-1 2
Thread-0 2
Thread-0 3
Thread-1 3
Thread-0 4
Thread-1 4
Thread-1 5
Thread-0 5
Thread-1 6
Thread-0 6
Thread-1 7
Thread-0 7
Thread-1 8
Thread-0 8
Thread-1 9
Thread-0 9
Thread-1 10
Thread-0 10
But the output isn't in sequence I want output as: Thread1 Output:1 Thread2 Output:1 Thread1 Output:2 Thread2 Output:2