多线程-synchronized锁在类级别和方法级执行结果的区别

synchronized 方法级别代码:

public class Thread1 {
    private int num = 0;
    public synchronized void printNum(String arg){

        if (arg.equals("a")){
            num = 100;
            System.out.println("num value is "+ num);
            try {
                new Thread().sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else {
            num = 200;
            System.out.println("num value is "+ num);
        }
        System.out.println("tag = " + arg + " num = " + num);
    }

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

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                t1.printNum("a");
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                t2.printNum("b");
            }
        });

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

执行结果:

num value is 200
tag = b num = 200
num value is 100
tag = a num = 100

synchronized 类级别代码:

public class Thread1 {
    private static int num = 0;
    public static synchronized void printNum(String arg){

        if (arg.equals("a")){
            num = 100;
            System.out.println("num value is "+ num);
            try {
                new Thread().sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else {
            num = 200;
            System.out.println("num value is "+ num);
        }
        System.out.println("tag = " + arg + " num = " + num);
    }

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

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                t1.printNum("a");
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                t2.printNum("b");
            }
        });

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

执行结果:

num value is 100
tag = a num = 100
num value is 200
tag = b num = 200

总结:

关键字synchronized取得的锁都试对象锁,而不是把一段代码(方法)当做锁,所以十里代码中哪个线程限制性synchronized关键字的方法,哪个线程就持有该方法所属对象的锁(Lock),两个对象,线程获得的就是两个不通的锁,他们互补影响。
有一种情况则是相同的锁,即在静态方法上加synchronized关键字,表示锁定.class类,类一级别的锁(独占.class类)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值