学习笔记:java中synchronized锁的是对象还是方法

1.问题

synchronized是锁,但是锁住的内容究竟是对象还是方法。

2.测试

测试代码1(声明方法时加入synchronized):

public class MainActivity {

    public static void main(String[] args) {
        Thread thread1 = new Demo();//创建两个对象
        Thread thread2 = new Demo();


        thread1.start();
        thread2.start();
    }


}


class Demo extends Thread {
    public static int  i = 1;
    @Override
    public synchronized void run()
    {

        try {
            Thread.sleep(50);
            {
                for(int j = 1; j <= 5; j++)
                {
                    System.out.print("线程ID:"+Thread.currentThread().getId()+"打印"+i++ +"\n");
                }

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

测试代码2(加入synchronized (this)):

public class MainActivity {

    public static void main(String[] args) {
        Thread thread1 = new Demo();
        Thread thread2 = new Demo();


        thread1.start();
        thread2.start();
    }


}
class Demo extends Thread {
    public static int  i = 1;
    @Override
    public  void run() {
        synchronized (this)
        {
        try {
            Thread.sleep(50);
            {
                for (int j = 1; j <= 5; j++) {
                    System.out.print("线程ID:" + Thread.currentThread().getId() + "打印" + i++ + "\n");
                }

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    }
}

测试代码3(加入synchronized (Demo.class)):

public class MainActivity {

    public static void main(String[] args) {
        Thread thread1 = new Demo();
        Thread thread2 = new Demo();


        thread1.start();
        thread2.start();
    }


}
class Demo extends Thread {
    public static int  i = 1;
    @Override
    public  void run() {
        synchronized (Demo.class)
        {
        try {
            Thread.sleep(50);
            {
                for (int j = 1; j <= 5; j++) {
                    System.out.print("线程ID:" + Thread.currentThread().getId() + "打印" + i++ + "\n");
                }

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    }
}

结果预测:

如果锁的是方法,输出结果则应该为前5个线程ID相同,后5个线程ID相同,每次测试均是如此。

如果锁的是对象,输出结果则应该为乱序排列。

 

测试1结果:

线程ID:12打印2
线程ID:11打印1
线程ID:11打印3
线程ID:11打印4
线程ID:11打印5
线程ID:11打印6
线程ID:12打印7
线程ID:12打印8
线程ID:12打印9
线程ID:12打印10

测试2结果:

线程ID:12打印1
线程ID:12打印3
线程ID:11打印2
线程ID:12打印4
线程ID:12打印6
线程ID:12打印7
线程ID:11打印5
线程ID:11打印8
线程ID:11打印9
线程ID:11打印10

测试3结果(多次测试结果均是):

线程ID:11打印1
线程ID:11打印2
线程ID:11打印3
线程ID:11打印4
线程ID:11打印5
线程ID:12打印6
线程ID:12打印7
线程ID:12打印8
线程ID:12打印9
线程ID:12打印10

 

3.结论

显而易见,,synchronized,synchronized (this)锁的是对象,synchronized (Demo.class)锁的是方法。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值