user3841581 user3841581 - 1 month ago 13
Java Question

Setting a static variable in a run () method in java

I have a static variable which I would like to set in a run() method. I have the following:

public class Test{
public static int temp;
public static void main(String [] args)
{
update();
System.out.println("This is the content of temp"+temp);
}
public static void update()
{
(new Thread() {
@Override
public void run() {
// do some stuff
Test.temp=15;
}}).start();
}


I would like the content of temp to be updated to 15; but when I print it in the main function, it shows 0. How can this be fixed?

Answer

Threads working concurrently so you should wait until your new thread finishes:

public class Test{
   public static int temp;
   public static void main(String [] args) {
      update().join(); //we wait until new thread finishes
      System.out.println("This is the content of temp"+temp);
   }

   public static Thread update() {
       Thread t = new Thread() {
          @Override
          public void run() {
             // do some stuff
             Test.temp=15;
          }
       };
       t.start();
       return t;
    }
Comments