线程安全性(一) 原子性 基于锁的实现 - synchronized 修饰代码块

锁概述

锁是Java中除了AtomicXXX类之外,另一种实现原子性的方式,典型的两种基于锁实现原子性的方式是synchronized关键字和基于Lock接口的实现类;

synchronized关键字加锁
  • 依赖于JVM的锁实现,用synchronized关键字加锁;
  • synchronized关键字加的锁是不可中断锁,适合竞争不激烈,可读性好;
  • synchronized关键字加的锁在竞争激烈时性能下降的非常快;
Lock接口的实现类
  • 依赖于特殊的CPU指令,比如JDK中的java.util.concurrent.locks.Lock接口,比较有代表性的实现类有ReentrantLock;
  • Lock接口的实现类加的锁是可中断锁,竞争激烈时能维持常态;

synchronized能修饰的四种对象

  • 修饰代码块:被修饰的代码称作同步语句块,其作用范围是大括号括起来的代码,作用于调用的对象(可以自己指定锁定对象);如果代码块就是整个方法体,那么和修饰方式是等同的;
  • 修饰方法:被修饰的方法称为同步方法,作用范围是整个方法,作用于调用的对象(this)
  • 修饰静态方法:作用范围是整个静态方法,作用于这个类的所有对象,本质是对 Class 对象上锁
  • 修饰类:作用范围是synchronized后面的括号括起来的部分,作用于这个类的所有对象,本质是对 Class 对象上锁

synchronized修饰代码块示例 01 - 正例

  • 同一个对象不同线程中访问同步代码块,同步代码块对同一个调用对象是起到同步作用的;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class SynchronizedCodeBlock {

    public void test1(int j) {
        synchronized (this) {
            for (int i = 0; i < 10; i++) {
                log.info("synchronized block object {} - {}", j, i);
            }
        }
    }

    public static void main(String[] args) {
        testCodeBlockSync();
    }

    private static void testCodeBlockSync() {
        SynchronizedCodeBlock example1 = new SynchronizedCodeBlock();
        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(() -> {
            example1.test1(1);
        });
        service.execute(() -> {
            example1.test1(1);
        });
    }

}

输出:

  • 同一个对象所在的2个线程按顺序先后执行;
17:06:51.597 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 0
17:06:51.602 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 1
17:06:51.602 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 2
17:06:51.602 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 3
17:06:51.602 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 4
17:06:51.602 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 5
17:06:51.602 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 6
17:06:51.602 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 7
17:06:51.602 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 8
17:06:51.602 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 9
17:06:51.602 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 0
17:06:51.602 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 1
17:06:51.603 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 2
17:06:51.603 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 3
17:06:51.603 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 4
17:06:51.603 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 5
17:06:51.603 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 6
17:06:51.603 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 7
17:06:51.603 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 8
17:06:51.603 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 9

synchronized修饰代码块示例 02 - 反例

  • 不同对象不同线程中访问同步代码块,同步代码块对不同调用对象是不能起到同步作用的;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class SynchronizedCodeBlock {

    public void test1(int j) {
        synchronized (this) {
            for (int i = 0; i < 10; i++) {
                log.info("synchronized block object {} - {}", j, i);
            }
        }
    }

    public static void main(String[] args) {
        testCodeBlockNotSync();
    }

    private static void testCodeBlockNotSync() {
        SynchronizedCodeBlock example1 = new SynchronizedCodeBlock();
        SynchronizedCodeBlock example2 = new SynchronizedCodeBlock();
        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(() -> {
            example1.test1(1);
        });
        service.execute(() -> {
            example2.test1(2);
        });
    }

}

输出:

  • 乱序的,两个对象所在的线程同时执行;
17:07:52.278 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 2 - 0
17:07:52.278 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 0
17:07:52.284 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 2 - 1
17:07:52.284 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 1
17:07:52.285 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 2
17:07:52.285 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 2 - 2
17:07:52.285 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 3
17:07:52.285 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 2 - 3
17:07:52.285 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 4
17:07:52.285 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 2 - 4
17:07:52.285 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 5
17:07:52.285 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 6
17:07:52.285 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 7
17:07:52.285 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 2 - 5
17:07:52.285 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 8
17:07:52.285 [pool-1-thread-1] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 1 - 9
17:07:52.285 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 2 - 6
17:07:52.285 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 2 - 7
17:07:52.285 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 2 - 8
17:07:52.285 [pool-1-thread-2] INFO com.example.concurrency.example.SynchronizedCodeBlock - synchronized block object 2 - 9

synchronized修饰代码块示例 03 - run() 方法中的 this 是谁?

  • 答案:是 new Thread(instance) 中的 instance;
  • SynchronizedCodeBlock02 的 run() 方法对 this 加锁,创建 t1 和 t2 传入的 Runnable 都是 instance,故线程 t1 和 t2 都是对 instance 加锁,所以 t1 和 t2 的执行可以同步;
package com.example.concurrency.example.sync;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SynchronizedCodeBlock02 implements Runnable{

    static SynchronizedCodeBlock02 instance = new SynchronizedCodeBlock02();

    @Override
    public void run() {
        synchronized (this) {
            log.info("{} start",Thread.currentThread());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("{} end",Thread.currentThread());
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(instance);
        Thread t2 = new Thread(instance);

        t1.start();
        t2.start();

        while (t1.isAlive() || t2.isAlive()) {

        }
        log.info("{} end", Thread.currentThread());
    }

}

输出:

21:50:16.719 [Thread-0] INFO com.example.concurrency.example.sync.SynchronizedCodeBlock02 - Thread[Thread-0,5,main] start
21:50:19.725 [Thread-0] INFO com.example.concurrency.example.sync.SynchronizedCodeBlock02 - Thread[Thread-0,5,main] end
21:50:19.725 [Thread-1] INFO com.example.concurrency.example.sync.SynchronizedCodeBlock02 - Thread[Thread-1,5,main] start
21:50:22.725 [Thread-1] INFO com.example.concurrency.example.sync.SynchronizedCodeBlock02 - Thread[Thread-1,5,main] end
21:50:22.725 [main] INFO com.example.concurrency.example.sync.SynchronizedCodeBlock02 - Thread[main,5,main] end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容