Thread safety for static variables

前端 未结 4 1479
天涯浪人
天涯浪人 2021-02-19 03:12
class ABC implements Runnable {
    private static int a;
    private static int b;
    public void run() {
    }
}

I have a Java class as above. I hav

4条回答
  •  佛祖请我去吃肉
    2021-02-19 03:42

    Use a synchronized method, e.g.

    public synchronized void increment()
    {
      a++; b++;
      // push in to hash table.
    }
    

    The above is good if you are accessing the statics through a single instance, however if you have multiple instances, then you need to synchronize on some static object - something like (untested)..

    private static Object lock = new Object();
    

    in the method

    public void increment()
    {
      synchronize(lock)
      {
        a++;b++;
        // do stuff
      }
    }
    

    NOTE: These approaches assume that you want to increment a and b in one atomic action, the other answers highlight how they can be individually incremented using atomics.

提交回复
热议问题