原子性-锁synchronized


老马说编程
synchronized
可以修饰
1.实例方法
2.static方法
3.代码块

synchronized 实例方法

锁的是this ,就是对象本身,就是说 有线程在调用这个实例的incr方法,其他线程不能同时调用incr和getCount方法

public class Counter {

    private int count;

    public synchronized void incr(){
        count ++;
    }
    
    public synchronized int getCount() {
        return count;
    }

}

synchronized 静态方法

这样锁的是类对象,就是StaticCounter.class

public class StaticCounter {
    private static int count = 0;

    public static synchronized void incr() {
        count++;
    }

    public static synchronized int getCount() {
        return count;
    }
}

代码块

可以保护任意对象 ,显示指定
synchronized(随便什么对象,Counter3 .class可以,this也可以)

public class Counter3 {

    private int count;
    private Object lock = new Object();
    
    public void incr(){
        synchronized(lock){
            count ++;    
        }
    }
    
    public int getCount() {
        synchronized(lock){
            return count;
        }
    }
}

例子 锁this

@Slf4j
public class SynchronizedExample1 {

    // 修饰一个代码块
    public void test1(int j) {
        synchronized (this) {
            for (int i = 0; i < 10; i++) {
                log.info("test1 {} - {}", j, i);
            }
        }
    }

    // 修饰一个方法
    public synchronized void test2(int j) {
        for (int i = 0; i < 10; i++) {
            log.info("test2 {} - {}", j, i);
        }
    }

    public static void main(String[] args) {

        //不同的实例 执行不会被锁 因为只锁this
        SynchronizedExample1 example1 = new SynchronizedExample1();
        SynchronizedExample1 example2 = new SynchronizedExample1();

        //线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(() -> {
           // example1.test1(1);
            example1.test2(1);
        });
        // executorService.execute不会等上一个 executorService.execute执行完毕
        executorService.execute(() -> {
           // example2.test1(2);
            example2.test2(2);
        });

        //输出结果表明二个线程交替
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容