I tried to write a program that uses threads, but couldn't understand the o/p. I have 2 thread: s
and t
. But I can't see that thread s
is working.
Can anyone please explain to me the behavior? Thanks
My code:
public class Bground implements Runnable
{
Thread t,s;
Bground()
{
t = new Thread(this,"first thread");
s = new Thread(this,"second thread");
s.start();
t.start();
}
public void run()
{
System.out.println("inside run" + t.getName());
try
{
for (int i = 0; i < 5; i++)
{
System.out.println("In child thread" + i);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String argv[])
{
Bground b = new Bground();
try
{
for (int i = 0; i < 5; i++)
{
System.out.println("In main thread" + i);
Thread.sleep(1);
}
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
O/P:
c:\Program Files\Java\jdk1.6.0_23\bin>java Bground
In main thread0
inside runfirst thread
inside runfirst thread
In child thread0
In child thread1
In child thread2
In main thread1
In child thread3
In child thread0
In child thread1
In child thread2
In child thread3
In child thread4
In main thread2
In child thread4
In main thread3
In main thread4
Thread.sleep(1000)
. The argument is in milliseconds. – Thorbjørn Ravn Andersen