Which is the difference between AtomicReference and Synchronized?

前端 未结 3 1146
独厮守ぢ
独厮守ぢ 2021-02-07 22:48

Is there any difference between AtomicReference and Synchronized?
E.G.

public class Internet {
    AtomicReference address;
    public String g         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-07 23:29

    A synchronized method/block blocks all access to that method/block from other threads while one thread is performing the method.

    An Atomic... can be accessed by many threads at once - there are usually CAS access methods available for them to help with high-speed access.

    As such - they are completely different but they can sometimes be used to solve parallel accessibility issues.

    These two classes use the two different methods to return a steadily increasing number such that the same number will never be delivered twice. The AtomicInteger version will run faster in a high-load environment. The one using synchronized will work in Java 4 and older.

    public class Incremental1 {
    
        private AtomicInteger n = new AtomicInteger();
    
        public Integer nextNumber() {
            // Use the Atomic CAS function to increment the number.
            return n.getAndIncrement();
        }
    }
    
    public class Incremental2 {
    
        private int n = 0;
    
        public synchronized Integer nextNumber() {
            // No two threads can get in here at the same time.
            return n++;
        }
    
    }
    

提交回复
热议问题