user3789200
user3789200

Reputation: 1186

Calling the run method in a thread

Here I have created the class Main and inside it a thread t1 had been start by sending it a runnable target. But since the thread has been started I believe the run() method, should run and call a.SetI(20) method. But the output gives as 0. Could somone please let me know the logic behind this.

public class _216 {

    private int i;

    public synchronized void setI(int i){
    this.i=i;
    }
    public synchronized int getI(){
    return i;
    }


}

class Main{
    public static void main(String[] args) {
        final _216 a=new _216();
        Runnable r=new Runnable(){

            @Override
            public void run() {

            a.setI(20);
            }

        };
        Thread t1=new Thread(r);
        t1.start();

        System.out.println(a.getI());
    }
}

Upvotes: 0

Views: 41

Answers (3)

Neverwork2123
Neverwork2123

Reputation: 227

You very well may be printing the result before the thread completes running.

At that point in time the threads may be running simultaneously.

Also recognize that i is never initialized until you call setI, consider hardcoding a default value.

Upvotes: 1

Sushant Tambare
Sushant Tambare

Reputation: 526

You should use t1.join() so that both main and this new thread will joined and later code will continue to print.

Here

Thread t1=new Thread(r);
t1.start();
t1.join()

    System.out.println(a.getI());

Upvotes: 1

user207421
user207421

Reputation: 311046

The 'logic behind this' is that the thread may not have executed yet when you do your print.

Upvotes: 2

Related Questions