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() {
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With