user2991252
user2991252

Reputation: 788

Pass integer to running thread in java

I have a problem in Java with threads. I am trying to pass an integer from the mainthread to another running thread in Java - but the value is always 0. Is there a way to solve this? I guess the reason why this happends is that threads have their own lives.

Here is the class that receives the integer - via an accessor-method. Then its supposed to be printed in the print-method - but as I mentioned, the value is ZERO.

  class MyThread implements Runnable {


     private int val;

     public void run() {

         printVal();
     }

     public void setValue(int val) {
         this.val = val;
     }

     private void printVal() {

             while (true) {
                 System.out.println("val: " + this.val);

             try {
                 Thread.sleep(1000);
             } catch (InterruptedException ie) {

             }
         }
     }  
   }

Upvotes: 1

Views: 642

Answers (1)

RMachnik
RMachnik

Reputation: 3684

It seems that you got an obstacle made by cached value of variable. To solve it, please declare your int as volatile

private volatile int mainVal;

so that int will not be cached. Now you can pass it to other threads without cache effect.

Upvotes: 3

Related Questions