synchronized到底锁的是谁、何时生效

本文主要介绍了Java中synchronized锁的几种形式,包括修饰普通方法、静态方法和代码块。通过多个示例展示了不同情况下锁的生效机制,如普通方法锁定当前对象,静态方法锁定当前类,代码块锁定括号中的对象或类,并给出了相应的结论。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、synchronized锁的几种形式

  1. synchronized修饰普通方法
  2. synchronized修饰静态方法
  3. synchronized修饰代码块

1、synchronized修饰普通方法

简单示例

public class Test{

    private String age;
    private String name;

    public synchronized void print(String arg1, String arg2) {
        this.age = this.age + arg1;
        this.name = this.name + arg2;
    }
}

下面看一个稍微复杂的场景,main方法中启动两个线程,func1和func2均被synchronized修饰。
由于是非静态方法,锁的是当前对象data,由于func1和func2方法都被synchronized修饰,且在main方法中,是用的new出来的同一个data进行调用,于是锁的就是这个data,用到data发生资源抢占,需要排队。代码首先执行到func1,func1执行3秒,func2排队等待三秒后,执行func2。

public class Test{

    public static void main(String[] args) {
        Data data = new Data();
        new Thread(data::func1).start();
        new Thread(data::func2).start();
    }
}

class Data{

    SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");

    public synchronized void func1(){
        System.out.println("func1开始执行,当前时间"+ sbf.format(new Date()));
        try {
            System.out.println("func1休息3秒,当前时间"+sbf.format(new Date()));
            Thread.sleep(3000);
            System.out.println("func1休息3秒结束,当前时间"+sbf.format(new Date()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("func1:1111111111111111111111111111111111111111111111111");
        System.out.println("func1执行结束,当前时间"+ sbf.format(new Date()));
    }

    public synchronized void func2(){
        System.out.println("func2开始执行,当前时间"+ sbf.format(new Date()));
        System.out.println("func2:22222222222222222222222222222222222222222222222222");
        System.out.println("func2执行结束,当前时间"+ sbf.format(new Date()));
    }
}

在这里插入图片描述

但如果把func2方法的synchronized修饰去掉,那么运行结果如下。
因为去掉synchronized的func2不再参与data资源的抢占,main方法启动后,func的线程和func2的线程同时启动,首先到达线程1,但因为需要等待3秒,于是func2的结果率先输出,3秒后再输出func1的结果

public class Test{

    public static void main(String[] args) {
        Data data = new Data();
        new Thread(data::func1).start();
        new Thread(data::func2).start();
    }
}

class Data{

    SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");

    public synchronized void func1(){
        System.out.println("func1开始执行,当前时间"+ sbf.format(new Date()));
        try {
            System.out.println("func1休息3秒,当前时间"+sbf.format(new Date()));
            Thread.sleep(3000);
            System.out.println("func1休息3秒结束,当前时间"+sbf.format(new Date()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("func1:1111111111111111111111111111111111111111111111111");
        System.out.println("func1执行结束,当前时间"+ sbf.format(new Date()));
    }

    public void func2(){
        System.out.println("func2开始执行,当前时间"+ sbf.format(new Date()));
        System.out.println("func2:22222222222222222222222222222222222222222222222222");
        System.out.println("func2执行结束,当前时间"+ sbf.format(new Date()));
    }
}

在这里插入图片描述

此时再做一个变化,func1和func2仍然使用synchronized修饰,但main方法中调用func1与func2每次都是新new出来的Data对象,因为普通方法锁定的是同一个对象,而不同的对象直接不发生资源抢占,因此func2无需等待func1执行完毕再执行,而是和func1同步执行。

public class Test{

    public static void main(String[] args) {
        new Thread(new Data()::func1).start();
        new Thread(new Data()::func2).start();
    }
}

class Data{

    SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");

    public synchronized void func1(){
        System.out.println("func1开始执行,当前时间"+ sbf.format(new Date()));
        try {
            System.out.println("func1休息3秒,当前时间"+sbf.format(new Date()));
            Thread.sleep(3000);
            System.out.println("func1休息3秒结束,当前时间"+sbf.format(new Date()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("func1:1111111111111111111111111111111111111111111111111");
        System.out.println("func1执行结束,当前时间"+ sbf.format(new Date()));
    }

    public synchronized void func2(){
        System.out.println("func2开始执行,当前时间"+ sbf.format(new Date()));
        System.out.println("func2:22222222222222222222222222222222222222222222222222");
        System.out.println("func2执行结束,当前时间"+ sbf.format(new Date()));
    }
}

在这里插入图片描述

2. synchronized修饰静态方法

简单示例

public class Test {

    public synchronized static void print(String arg1, String arg2) {
        System.out.println("静态方法锁");
    }
}

继续使用标题1中的例子,将func1及func2都修改为静态方法,然后在main方法中,new出来两个data对象分别调用,看下面的执行结果,发现虽然是两个对象,但仍然发生了资源抢占,因此synchronized修饰静态方法,锁定是当前类而不是当前对象。

同样的,去掉其中一个方法的synchronized修饰,则不会进行排队。

public class Test {

    public static void main(String[] args)  {
        new Thread(()->new Data().func1()).start();
        new Thread(()->new Data().func2()).start();
    }
}

class Data {

    static SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");

    public synchronized static void func1() {
        System.out.println("func1开始执行,当前时间" + sbf.format(new Date()));
        try {
            System.out.println("func1休息3秒,当前时间" + sbf.format(new Date()));
            Thread.sleep(3000);
            System.out.println("func1休息3秒结束,当前时间" + sbf.format(new Date()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("func1:1111111111111111111111111111111111111111111111111");
        System.out.println("func1执行结束,当前时间" + sbf.format(new Date()));
    }

    public synchronized static void func2() {
        System.out.println("func2开始执行,当前时间" + sbf.format(new Date()));
        System.out.println("func2:22222222222222222222222222222222222222222222222222");
        System.out.println("func2执行结束,当前时间" + sbf.format(new Date()));
    }
}

在这里插入图片描述

3. synchronized修饰代码块

简单示例

public class Test{

    private String age;
    private String name;

    private Object object = new Object();
    
    public void print(String arg1, String arg2) {
        synchronized (object) {
            this.age = this.age + arg1;
        }
        this.name = this.name + arg2;
    }
}

继续用标题1中的例子修改,起5个线程,去调用func1,func1调用func2,且将func2包裹在同步代码块中,用synchronized修改,锁定this对象,而this指的就是当前Data对象的实例化对象,因此五个线程均发生了资源抢占,挨个按顺序执行。synchronized同步代码块可圈定最小的锁范围,提高效率。

public class Test {

    public static void main(String[] args) {
        Data data = new Data();
        for (int i = 0; i < 5; i++) {
            new Thread(data::func1).start();
        }
    }
}

class Data {

    static SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");

    public void func1() {
        System.out.println("func1开始执行,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
        System.out.println("在func2执行之前先做点不需要排队没有并发问题的事情" + ",当前线程" + Thread.currentThread());
        // 此处锁定this对象
        synchronized (this) {
            func2();
        }
        System.out.println("func1执行结束,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
    }

    public void func2() {
        try {
            // 休息三秒
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("func2:22222222222222222222222222222222222222222222222222,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
    }
}

在这里插入图片描述
同样的,若将main方法中调用func1的对象,每次都新new出来一个采用不同的对象,则不会进行排队。

public class Test {

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            // 每次都是不同的对象
            new Thread(new Data()::func1).start();
        }
    }
}

class Data {

    static SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");

    public void func1() {
        System.out.println("func1开始执行,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
        System.out.println("在func2执行之前先做点不需要排队没有并发问题的事情" + ",当前线程" + Thread.currentThread());
        // 此处锁定this对象
        synchronized (this) {
            func2();
        }
        System.out.println("func1执行结束,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
    }

    public void func2() {
        try {
            // 休息三秒
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("func2:22222222222222222222222222222222222222222222222222,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
    }
}

在这里插入图片描述
但将锁定对象换为new InstanceTest(),也没有触发排队,因为每次锁的对象都是新new出来的,锁的不是同一个,虽然调用的对象是同一个。

public class Test {

    public static void main(String[] args) {
        // 调用是同一个对象
        Data data = new Data();
        for (int i = 0; i < 5; i++) {
            new Thread(data::func1).start();
        }
    }
}

class Data {

    SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");

    public void func1() {
        System.out.println("func1开始执行,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
        System.out.println("在func2执行之前先做点不需要排队没有并发问题的事情" + ",当前线程" + Thread.currentThread());
        // 此处锁定new InstanceTest()对象
        synchronized (new InstanceTest()) {
            func2();
        }
        System.out.println("func1执行结束,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
    }

    public void func2() {
        try {
            // 休息三秒
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("func2:22222222222222222222222222222222222222222222222222,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
    }
}

在这里插入图片描述
将锁定对象InstanceTest移到func1方法外面变成Data类的成员变量:private InstanceTest instanceTest = new InstanceTest();,调用仍然是同一个data对象,因此Data类中new出来的InstanceTest也是同一个对象,因此会发生排队。

public class Test {

    public static void main(String[] args) {
        // 调用是同一个对象
        Data data = new Data();
        for (int i = 0; i < 5; i++) {
            new Thread(data::func1).start();
        }
    }
}

class Data {

    SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");

    private InstanceTest instanceTest = new InstanceTest();

    public void func1() {
        System.out.println("func1开始执行,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
        System.out.println("在func2执行之前先做点不需要排队没有并发问题的事情" + ",当前线程" + Thread.currentThread());
        // 此处锁定instanceTest对象
        synchronized (instanceTest) {
            func2();
        }
        System.out.println("func1执行结束,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
    }

    public void func2() {
        try {
            // 休息三秒
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("func2:22222222222222222222222222222222222222222222222222,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
    }
}

在这里插入图片描述
将锁定的对象换为Integer xxx = 1;因为Integer拆箱共享常量池,只有一份,则发生排队

public class Test {

    public static void main(String[] args) {
        // 调用是同一个对象
        Data data = new Data();
        for (int i = 0; i < 5; i++) {
            new Thread(data::func1).start();
        }
    }
}

class Data {

    SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");

    public void func1() {
        System.out.println("func1开始执行,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
        System.out.println("在func2执行之前先做点不需要排队没有并发问题的事情" + ",当前线程" + Thread.currentThread());
        // 此处锁定Integer instanceTest = 1对象
        Integer instanceTest = 1;
        synchronized (instanceTest) {
            func2();
        }
        System.out.println("func1执行结束,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
    }

    public void func2() {
        try {
            // 休息三秒
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("func2:22222222222222222222222222222222222222222222222222,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
    }
}

在这里插入图片描述
但如果将Integer new出来对象,产生了多个不同的Integer对象,就不会排队

public class Test {

    public static void main(String[] args) {
        // 调用是同一个对象
        Data data = new Data();
        for (int i = 0; i < 5; i++) {
            new Thread(data::func1).start();
        }
    }
}

class Data {

    SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");

    public void func1() {
        System.out.println("func1开始执行,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
        System.out.println("在func2执行之前先做点不需要排队没有并发问题的事情" + ",当前线程" + Thread.currentThread());
        // 此处锁定new Integer()对象
        Integer instanceTest = new Integer(1);
        synchronized (instanceTest) {
            func2();
        }
        System.out.println("func1执行结束,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
    }

    public void func2() {
        try {
            // 休息三秒
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("func2:22222222222222222222222222222222222222222222222222,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
    }
}

在这里插入图片描述
将锁定的Integer instanceTest = 1;修改为Integer instanceTest = 128;不发生排队。因为jdk自动拆箱,–128到127之间的值在内存中会被重复利用,认为是一个对象,而超过这个范围的值将会被加载为多个对象,每来一次new一个Integer。因此未发生排队

public class Test {

    public static void main(String[] args) {
        // 调用是同一个对象
        Data data = new Data();
        for (int i = 0; i < 5; i++) {
            new Thread(data::func1).start();
        }
    }
}

class Data {

    SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");

    public void func1() {
        System.out.println("func1开始执行,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
        System.out.println("在func2执行之前先做点不需要排队没有并发问题的事情" + ",当前线程" + Thread.currentThread());
        // 此处锁定new InstanceTest()对象
        Integer instanceTest = 128;
        synchronized (instanceTest) {
            func2();
        }
        System.out.println("func1执行结束,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
    }

    public void func2() {
        try {
            // 休息三秒
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("func2:22222222222222222222222222222222222222222222222222,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
    }
}

在这里插入图片描述

此时我锁类。因为类只有一个,因此会发生排队

public class Test {

    public static void main(String[] args) {
        // 调用是同一个对象
        Data data = new Data();
        for (int i = 0; i < 5; i++) {
            new Thread(data::func1).start();
        }
    }
}

class Data {

    SimpleDateFormat sbf = new SimpleDateFormat("HH:mm:ss");

    public void func1() {
        System.out.println("func1开始执行,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
        System.out.println("在func2执行之前先做点不需要排队没有并发问题的事情" + ",当前线程" + Thread.currentThread());
        // 此处锁定new Data()对象
        synchronized (Data.class) {
            func2();
        }
        System.out.println("func1执行结束,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
    }

    public void func2() {
        try {
            // 休息三秒
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("func2:22222222222222222222222222222222222222222222222222,当前时间" + sbf.format(new Date()) + ",当前线程" + Thread.currentThread());
    }
}

在这里插入图片描述

二、结论

1. synchronized修饰普通方法

锁定的是当前对象,当前方法的调用对象若是new出来的多份,则不发生资源抢占;只有同一个对象调用该方法时,synchronized锁才生效。

2. synchronized修饰静态方法

锁定是当前类,不论是用类调用的该方法,还是用new出来的一个或N个对象调用的该方法,都会发生资源抢占。

3. synchronized修饰代码块

锁定的是括号中的对象或类。可以认为是结合了1与2的优点与方式。括号中的对象若是一份,则synchronized锁生效,否则无效。生效情况如下:

  • 括号中的对象为this,且调用该方法的对象为同一个
  • 不论调用该方法的对象是不是同一个,括号中的对象永远是同一个,比如:Integer xxx = 1;
  • 括号中为类
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值