简体   繁体   中英

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) {

             }
         }
     }  
   }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM