简体   繁体   English

将整数传递给java中正在运行的线程

[英]Pass integer to running thread in java

I have a problem in Java with threads. 我在Java中遇到线程问题。 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? 我试图从mainthread传递一个整数到Java中的另一个运行线程 - 但值总是为0.有没有办法解决这个问题? 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 要解决它,请将您的int声明为volatile

private volatile int mainVal;

so that int will not be cached. 这样int就不会被缓存了。 Now you can pass it to other threads without cache effect. 现在您可以将其传递给其他没有缓存效果的线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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