I understand that sleep()
is used to sleep a thread for specified time. I made tow examples - in example 1 I am getting output as 1
,2
, 3
,4
because I created only one. In example 2, I created 2 instances of the thread and I'm getting output 1
,1
,2
,2
,3
,3
,4
,4
.
Why the output is not 1
,2
, 3
, 4
for the first thread followed by 1
,2
,3
,4
for the second one?.
Example 1:
// Using sleep() method
public class Aaa extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{
Thread.sleep(500);
} catch(InterruptedException e){
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String[] args){
Aaa m1=new Aaa();
m1.start();
}
}
Output:
1
2
3
4
Example 2:
// Using sleep() method
public class Aaa extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{
Thread.sleep(500); // sleeps thread
} catch(InterruptedException e){
System.out.println(e);
}
System.out.println(i);
}
}
public static void main(String[] args){
Aaa m1=new Aaa(); // creating one object
Aaa m2=new Aaa(); // creating second object of a class
m1.start(); // calls run method
m2.start();
}
}
Output:
1
1
2
2
3
3
4
4