class
Test {
public static void main(
String args[])
{
try{
MyThread m=new MyThread();
MyThread m1=new MyThread();
m.start();
System.out.println("main method");
m.join(800);
m1.start();
System.out.println(" elapsed 800 milliseconds");
m1.join(1000);
System.out.println("elapsed 1000 milliseconds");
}catch(Exception ie){}
}//main
}//Test
class MyThread extends
Thread {
public void run()
{
for(int i=1;i<=5;i++)
{
try{ Thread.sleep(500);}catch(InterruptedException ie){}
System.out.println(getName() );
}//for
}//run
}//MyThread
Output:
main method
Thread-0
elapsed 800 milliseconds
Thread-0
Thread-1
Thread-0
Thread-1
elapsed 1000 milliseconds
Thread-0
Thread-1
Thread-0
Thread-1
Thread-1
I understood the output ..this way,
m.join(800)- main thread has waited for 800 milliseconds, then s.o.p statment is executed
m1.join(1000) - main thread has waited for 1000milliseconds,then s.o.p is executed, now main thread is in dead state. m, m1 threads are running.
When i add synchronized keyword to run method of MyThread class...
public synchronized void run(){ /*same code */}
output is
main method
Thread-0 //line-1
Thread-0
Thread-0
Thread-0
Thread-0//line5
elapsed 800 milliseconds
Thread-1//line7
Thread-1
Thread-1
Thread-1
Thread-1//line11
elapsed 1000 milliseconds
Here, run method is synchronized , so second thread (m1) had to wait till first thread completes execution... but
why main thread is waiting more than 800 milliseconds ( at m.join(800))
and why main thread is waiting more than 1000 milliseconds?
( at m.join(1000) ).
I expected the output of first S.o.p between Line1-Line5 and output of second s.o.p between Line7- Line11. Becuase API says,
public final void join(long millis)
Waits at most millis milliseconds for this thread to die. , but here main thread is waiting more than specified no. of milliseconds.
Can any one of you explain pls.
Thanx in advance
Naresh
[ December 18, 2005: Message edited by: Naresh Kumar ]
atmost millis milliseconds [ December 18, 2005: Message edited by: Naresh Kumar ]