Synchronized关键字

一:synchronized的作用

一句话说出synchronized的作用: 能够保证在同一时刻最多只有一个线程执行该段代码,以达到保证并发安全的效果。

二:synchronized的地位

  • synchronized是Java的关键字,被Java原生的支持
  • 是最基本的互斥同步手段

三:不使用synchronized会带来什么样的后果?

public class DisappearRequest implements Runnable {
    static DisappearRequest instance = new DisappearRequest();
    static int i;
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(instance);
        Thread t2 = new Thread(instance);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(i);
    }
    @Override
    public void run() {
        i++;
    }
}

四:synchronized的用法

  • 对象锁:包含方法锁(默认锁对象为this当前实例对象)和同步代码块锁(自己指定锁对象)
public class SynchronizedObjectCodeBlock2 implements Runnable {

    static SynchronizedObjectCodeBlock2 instance = new SynchronizedObjectCodeBlock2();

    /** 指定自定义类锁 。*/
    Object lock = new Object();

    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()){
        }
        System.out.println("finished");
    }

    @Override
    public void run() {
        /** 若业务要求需要可使用不同类锁(lock1,lock2...)来同步代码块. */
        synchronized (this){
            System.out.println("我是"+Thread.currentThread().getName()+"拿到锁");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"运行结束");
        }
    }
}
  • 类锁:

    1.指synchronized修饰静态的方法或指定锁为class对象

    public class SynchronizedObjectMethod3 implements Runnable {

        static SynchronizedObjectMethod3 instance = new SynchronizedObjectMethod3();

        public static void main(String[] args) {
            Thread t1 = new Thread();
            Thread t2 = new Thread();
            t1.start();
            t2.start();
            while (t1.isAlive() || t2.isAlive()){
                
            }
            System.out.println("finished");
        }
        
        @Override
        public void run() {
            method();
        }
        
        private synchronized void method(){
            System.out.println("我是synchronize修饰的方法" + Thread.currentThread().getName());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("我是synchronize修饰的方法" + Thread.currentThread().getName()+"运行结束");
        }
        
    }

2.类锁的用法:

  • 概念(重要):Java类可能会有很多对象,但只有一个class对象
  • 形式1: synchronized加载static方法上
  • 形式2: synchronized(*.class)代码块
public class SynchronizedStaticClass4 implements Runnable {

    static SynchronizedStaticClass4 instance1 = new SynchronizedStaticClass4();
    static SynchronizedStaticClass4 instance2 = new SynchronizedStaticClass4();

    public static void main(String[] args) {
        Thread t1 = new Thread(instance1);
        Thread t2 = new Thread(instance2);
        t1.start();
        t2.start();
        while (t1.isAlive() || t2.isAlive()){

        }
        System.out.println("finished");
    }

    @Override
    public void run() {
        method();
    }

    /**
     * 不加static会出现两个线程同时方法此方法
     */
    private static synchronized void method(){
        System.out.println(Thread.currentThread().getName()+"进入方法锁");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"运行结束");
    }
}
public class SynchronizedClassClass5 implements Runnable {

    static SynchronizedClassClass5 instance1 = new SynchronizedClassClass5();
    static SynchronizedClassClass5 instance2 = new SynchronizedClassClass5();

    public static void main(String[] args) {
        Thread t1 = new Thread(instance1);
        Thread t2 = new Thread(instance2);
        t1.start();
        t2.start();
        while (t1.isAlive() || t2.isAlive()){

        }
        System.out.println("finished");
    }

    @Override
    public void run() {
        method();
    }

    private void method(){
        /**
         * 因为两个线程用的是不同的实例,所以要想实现同步,要么是static修饰的方法上加synchronized要么使用class类锁
         */
        synchronized (SynchronizedClassClass5.class){
            System.out.println(Thread.currentThread().getName()+"进入了方法");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"结束方法");
        }
    }
}

五:多线程方法同步方法的7种情况(面试常考)

  • 两个线程同时访问一个对象的同步方法
  • 两个线程同时访问两个对象的同步方法
  • 两个线程访问的是synchronized修饰的静态方法
  • 同时访问同步方法和非同步方法
  • 访问同一个对象的不同的普通同步方法 //虽然没有指定锁,但只要是同一个类下,默认都是this,所以两个同步方法无法串行运行
  • 同时访问静态synchronized和非静态synchronized方法
  • 方法抛异常后会释放锁 //synchronized锁住的内容出现异常会释放锁,lock需要手动释放锁

/**
 * create on 2020-12-22 17:10
 *  验证synchronized保护的内容发生运行时异常会释放锁
 *  例: 模拟一个线程等待另一个线程过程中,第一个线程抛出异常,第二个线程拿到锁
 **/
public class SynchronizedException8 implements Runnable {

    static SynchronizedException8 instance = new SynchronizedException8();

    public static void main(String[] args) {
        Thread t1 = new Thread(instance);
        Thread t2 = new Thread(instance);
        t1.start();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();
        while (t1.isAlive() || t2.isAlive()) {

        }
        System.out.println("finished");
    }

    @Override
    public void run() {
        if (Thread.currentThread().getName().equals("Thread-0")) {
            method1();
        }else {
            method2();
        }
    }

    public synchronized void method1(){
        System.out.println(Thread.currentThread().getName()+"进入method1");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        throw new  IllegalArgumentException(Thread.currentThread().getName()+"抛出异常");
    }

    public synchronized void method2(){
        System.out.println(Thread.currentThread().getName()+"进入method2");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"运行结束");
    }

}

六:七种情况总结:3点核心思想

  • 一把锁只能被一个线程获取,没有拿到锁的线程必须等待(对应1,5两种情况)
  • 每一个实例都对应自己的一把锁,不同实例之间互不影响,例:锁对象 *.class以及synchronized修饰的static方法,所有对象公用同一把锁(2,3,4,6情况)
  • 无论是方法正常执行完毕还是抛出异常,都会释放锁(对应7情况)

七:Synchronized性质

  • 可重入

    1.什么是可重入?指的是同一线程外层函数获取到锁之后,内层函数可直接再次获取锁。
    2.好处?避免死锁,提升封装性
    3.粒度?线程而非调用(三种情况说明和pthread的区别)

  • 不可中断

    一旦这个锁已经被别人获得了,如果我还想获得,我只能选择等待或者阻塞,知道别的线程释放了这个锁,如果别人永远不释放,我只能永远等待。

八:原理

  • 加锁和释放锁的原理:现象、时机、深入JVM看字节码

    Monditorenter和Moniditexit指令

  • 可重入原理:加锁次数计数器

    1.JVM负责跟踪对象被加锁的次数
    2.线程第一次给对象加锁的时候,计数变为1。每当这个相同的线程在此对象上再次获得锁,计数就会递增
    3.每当任务离开时,计数递减,当计数为0的时候,锁被完全释放

  • 保证可见性的原理:内存模型

九:Sychronized缺陷

  • 效率低:锁的释放情况少、试图获取锁的时候不能设置超时、不能中断一个试图获取锁的线程。
  • 不够灵活(读写锁更灵活):加锁和释放锁的时机单一,每个锁仅有单一条件(某个对象),可能是不够的
  • 无法知道是否成功的获得到锁(无法预知则无法提前做逻辑判断)

十:常见面试题

  • 使用注意点:锁对象不能为空、作用域不宜过大、避免死锁
  • 如何选择Lock和Sychronized关键字?尽可能使用concurrent包下的工具类,能使用Sychronized就别用Lock(减少代码编写量)非得Lock的时候才去使用Lock
  • 多线程访问同步方法的各种具体情况(前文已提)
文章资料整理于慕课网悟空老师课程视频
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值