I wanted to print 100 as output in the below program.
I am getting 0 as answer.
class s extends Thread{
int j=0;
public void run() {
开发者_StackOverflow中文版 try{Thread.sleep(5000);}
catch(Exception e){}
j=100;
}
public static void main(String args[])
{
s t1=new s();
t1.start();
System.out.println(t1.j);
}
}
You need to wait for the Thread
to finish..I have added a call to join for you, which will block and wait for the Thread
to complete before looking at the value of j
:
class s extends Thread{
int j=0;
public void run() {
try{ Thread.sleep(5000); } catch( Exception e ){}
j = 100;
}
public static void main(String args[]) throws InterruptedException {
s t1=new s();
t1.start();
t1.join() ; // Wait for t1 to finish
System.out.println(t1.j);
}
}
You have join the t1 to main.
So, the parent thread(main())
will wait till the child thread is complete.
Join t1
t1.join
so that the main thread will wait
Just join the thread t1 to main
t1.join
精彩评论