Thread safety for static variables

前端 未结 4 1470
天涯浪人
天涯浪人 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:34

    I would use AtomicInteger, which is designed to be thread-safe and is dead easy to use and imparts the absolute minimal of synchronization overhead to the application:

    class ABC implements Runnable {
        private static AtomicInteger a;
        private static AtomicInteger b;
        public void run() {
            // effectively a++, but no need for explicit synchronization!
            a.incrementAndGet(); 
        }
    }
    
    // In some other thread:
    
    int i = ABC.a.intValue(); // thread-safe without explicit synchronization
    

提交回复
热议问题