【问题标题】:Reflect changes made to a shared variable between two threads ,immediately as it is updated在两个线程之间反映对共享变量所做的更改,立即更新
【发布时间】:2016-05-12 08:22:30
【问题描述】:

这些只是询问我问题的示例代码,其他语句被省略 这里 NewClass 的实例同时传递给 Foot 和 Hand 对象 因此所有实例 NewClass、foot 和 hand 共享 NewClass 的变量 sno。

public class NewClass  {
     volatile int  sno = 100;

    public static void main(String args[])
    {
      NewClass n = new NewClass();  

      Foot f = new Foot(n); 
      Hand h = new Hand(n);

      f.start();
      h.start();

    }                
}

public class Foot implements Runnable{

    Thread t;
    NewClass n;
    public Foot(NewClass n)
    {
        this.n = n;
    }
    public void run(){
        for(int i=0;i<100;i++)
        {
            System.out.println("foot thread "+ i+" "+n.sno);
            n.sno=(-1)*n.sno;

             Thread.sleep(1); // surrounded by try-catch
        }
    }   
}

public class Hand implements Runnable {
    Thread t;
    NewClass n;
    public Hand(NewClass n)
    {
        this.n = n;
    }
    public void run(){
        for(int i=0;i<100;i++)
        {
            System.out.println("hand thread "+ i+" "+n.sno);
            n.sno=(-1)*n.sno;  
                Thread.sleep(1);  // surrounded by try -catch
        }
    }   
}

这里 seq.no 的符号每次都在变化,但是当被其他线程使用时,变化很多次都没有反映出来,好像更新需要时间。所以请帮忙,

【问题讨论】:

标签: java multithreading volatile


【解决方案1】:

更新时间不长。

System.out.println("foot thread " + i + " " + n.sno);
n.sno=(-1)*n.sno;

当您在两个并行运行的线程中发生这种情况时,它们可能同时将值视为正值。因此它们都将值更改为负值。如果你想控制变化,你需要一个信号量。

在新类中:

volatile int sno = 100;
final Object semaphore = new Object();

在你的两个 Runnables 中:

synchronized (n.semaphore) {
    System.out.println("foot thread " + i + " " + n.sno);
    n.sno = (-1) * n.sno;
}

【讨论】:

  • 谢谢,问题解决了,能不能多解释一下
  • 请不要忘记投票并接受答案。您需要我更详细地解释答案的哪一部分?
  • 好的,semaphore 是如何解决更新问题的,哪个部分应该在同步块中,要更新的部分还是要读取的部分。
  • 我无法加入聊天我是 stackoverflow 的新手。所以如果你能给我上面的解释,这将非常有帮助,因为我需要在其他地方应用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多