在更新时立即反映对两个线程之间的共享变量所做的更改

Reflect changes made to a shared variable between two threads ,immediately as it is updated

这些只是问我问题的示例代码,其他语句被省略 这里 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 的符号每次都在变化,但是当被其他线程使用时,变化很多次都没有反映出来,好像正在更新 time.so 请帮忙,

更新时间不长。

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

当您在两个并行线程 运行 中发生这种情况时,它们可能会同时观察到该值为正值。所以他们都将值更改为负值。如果你想控制变化,你需要一个信号量。

在新班级中:

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

在你的两个 Runnable 中:

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