Basically this code has two threads created in two classes, and they are called from the third class. Each thread has a loop, and it sleeps after each iteration.
(code is in the end)
The output is:
CHECK 0 CHECK
CHECK 1 CHECK
run one
in thread1
CHECK 2 CHECK
run two
in thread2
1) I am not getting any idea why it works this way. I mean it is okay that CHECK 0 CHECK should be printed first. But why does CHECK 1 CHECK get printed before Thread1 (whereas it comes after Thread1 is called in the code) and same for CHECK 2 CHECK and Thread2?
2) If i replace CHECK 2 CHECK with System.exit(0), as in the case above, where printing CHECK 2 CHECK, which is next to Thread2, takes place before running Thread2, Why is System.exit(0) happening after running Thread2 in this case?
Output for second case:
CHECK 0 CHECK
CHECK 1 CHECK
run one
in thread1
run two
in thread2
Please tell why this is happening? Why are the threads and code in method, getting mixed up this way?
I think i don't have any idea about how threads are managed by java. I tried searching a lot, but could not find anything that i could understand.
Code:
public class Thread1 implements Runnable
{
public Thread1()
{
new Thread(this).start();
}
public void run()
{
// TODO Auto-generated method stub
System.out.println("run one");
try
{
for(int i = 0; i < 5;i++)
{
System.out.println("in thread1 ");
Thread.sleep(1000);
}
}
catch(Exception e)
{
//e.printStackTrace();
}
}
}
public class Thread2 implements Runnable
{
public Thread2()
{
new Thread(this).start();
}
public void run()
{
// TODO Auto-generated method stub
System.out.println("run two");
try
{
for(int i=0;i<5;i++)
{
System.out.println("in thread2 ");
Thread.sleep(1000);
}
}
catch(Exception e)
{
//e.printStackTrace();
}
}
}
public class Threadjava
{
public static void main(String[] str)
{
System.out.println("CHECK 0 CHECK");
new Thread1();
System.out.println("CHECK 1 CHECK");
new Thread2();
System.out.println("CHECK 2 CHECK");
//The above is deleted in the second case
System.exit(0);
System.out.println("CHECK 3 CHECK");
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…