美文网首页
synchronized方法

synchronized方法

作者: 大风过岗 | 来源:发表于2020-11-03 14:27 被阅读0次

    案例

    问: 线程A在T 时刻调用addA()方法,线程B能否在T 时刻同时调用方法addB()?

    public class SyncX {
    
        private int a;
        private int b;
    
        public synchronized void addA(){
            a++;
        }
    
        public synchronized void addB(){
            b++;
        }
    }
    
    

    声明了synchronized的方法,在执行时,线程需要获取该对象的锁(即:this对象的锁),同一个对象内部的各个同步方法的锁是相同的,所以 方法addA() 和 addB() 在同一时刻,只能有一个正在运行

    官方文档说明

    Oracle文档

    public class SynchronizedCounter {
        private int c = 0;
    
        public synchronized void increment() {
            c++;
        }
    
        public synchronized void decrement() {
            c--;
        }
    
        public synchronized int value() {
            return c;
        }
    }
    If count is an instance of SynchronizedCounter, then making these methods synchronized has two effects:
    
    First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
    
    
    Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.
    

    First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
    Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

    总结

    同步方法有俩种效果:

    1. 首先,它保证了: 对同一个对象内部的同步方法的俩个调用不会出现交错运行,即:同一时刻只能有一个线程在执行同一对象的同步方法。当一个线程在执行一个对象的同步方法时,所有调用此对象同步方法的其他线程必须阻塞住,直到第一个线程执行完毕.
    2. 第二,当一个同步方法退出之后,它会自动与后续在相同对象上的同步方法的调用,建立happens-before关系.这样做保证了: 对一个对象状态的改变对其他所有线程都是可见的。即: 同一对象的synchronized方法之间存在happens-before关系.

    参考文档

    1. 同步方法
    2. wait方法为什么一定要在同步代码中
    3. 其他
    4. oracle文档

    相关文章

      网友评论

          本文标题:synchronized方法

          本文链接:https://www.haomeiwen.com/subject/vwibvktx.html