synchronized 锁住了什么

先上结论:

  类方法中,synchronized锁住的是对象this,只有调用同一个对象的方法才需要获取锁。同时,同一个对象中所有加了synchronize的方法只能一次调用一个

  静态方法中,synchronized锁的是整个类对象,类似于(X.class),该类中所有加了synchronized的静态方法,一次只能调用一个

class Sync {

    public synchronized void test() {
        System.out.println("test开始..");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("test结束..");
    }

    public synchronized void test2() {
        System.out.println("test2开始..");
        try {
            Thread.sleep(800);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("test2结束..");
    }
}

class MyThread extends Thread {

    private Sync sync;

    public MyThread(Sync sync) {
        this.sync = sync;
    }

    public void run() {
        sync.test();
    }
}

class MyThread2 extends Thread {

    private Sync sync;

    public MyThread2(Sync sync) {
        this.sync = sync;
    }

    public void run() {
        sync.test2();
    }
}

public class Main {

    public static void main(String[] args) {
        Sync sync = new Sync();
        Thread thread = new MyThread(sync);
        Thread thread2 = new MyThread2(sync);
        thread.start();
        thread2.start();

    }
}

运行结果:

test开始..
test结束..
test2开始..
test2结束..

方案是按顺序执行的,说明了锁住的是同一个对象:

main方法换成以下写法:

public static void main(String[] args) {
        Thread thread = new MyThread(new Sync());
        Thread thread2 = new MyThread2(new Sync());
        thread.start();
        thread2.start();
}

结果:

test开始..
test2开始..
test2结束..
test结束..

synchronized没有起到同步作用,说明不是同一个锁

静态方法:

class Sync {

    public static synchronized void test() {
        System.out.println("test开始..");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("test结束..");
    }

    public static synchronized void test2() {
        System.out.println("test2开始..");
        try {
            Thread.sleep(800);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("test2结束..");
    }
}

class MyThread extends Thread {

    public void run() {
        Sync.test();
    }
}

class MyThread2 extends Thread {

    public void run() {
        Sync.test2();
    }
}

public class Main {

    public static void main(String[] args) {
        Thread thread = new MyThread();
        Thread thread2 = new MyThread2();
        thread.start();
        thread2.start();

    }
}

运行结果:

test开始..
test结束..
test2开始..
test2结束..

本文参考了叉叉哥 的博客:Java线程同步:synchronized锁住的是代码还是对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值