Update the attributes of a java object from a thread?

The value of the variable var is always 0. IT is almost as if the method was never called. I would like to be able to change the value of val from inside the thread and if I call getVal() I would like to be able to have access to the new value.

public class Test1 {
    private int val;

    public Test1() {
        val=0;
    }

    public void changeVal() {

        new Thread(new Runnable() {
            public void run() {
                val=1;
            }
        }).start();
    }

    public int getVal() {
        return this.val;
    }

    public static void main(String[]args) {
        Test1 x=new Test1();
        x.changeVal();
        System.out.println("VAl: "+x.getVal() );
    }
}

You have set up a race condition between your statement

  x.changeVal();

and

 System.out.println("VAL: "+x.getVal() );

Try putting the following code between the above two statements.

    try {
        Thread.sleep(100);
    }
    catch (Exception e) {
        System.out.println("Exception: " + e);
    }

This gives your new thread a chance to be established before you reach the println statement.

The value is changed, however getVal() is (most of the time) executed before var=1 in method ‘run’. The order of execution is controled by thread scheduler, but as told by Johnny Mopp, adding .join() will fix it.

  public void changeVal() throws InterruptedException {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                val = 1;

            }

        });
        t.start();
        t.join();

    }

    public static void main(String[] args) throws InterruptedException {
        Test1 x = new Test1();
        x.changeVal();

        System.out.println("VAl: " + x.getVal());
    }

you need to change your main method like below:

public static void main(String[]args)
 {
    Test1 x=new Test1();
    x.changeVal();
   try {
        Thread.sleep(100);//sometime here 
    }
    catch (Exception e) {
        System.out.println("Exception: " + e);
    }
    System.out.println("VAl: "+x.getVal() );

 }

Or

You can use Thread.join(); to join Main thread with child thread in changeVal() method.