Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to do in order to print 100?

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); 
        } 

}
like image 526
Abi Avatar asked Jan 14 '11 13:01

Abi


1 Answers

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); 
    } 
}
like image 81
tim_yates Avatar answered Oct 21 '22 03:10

tim_yates