synchronized作用this monitor和Class monitor

 1、this monitor

synchronized关键字直接写在非静态方法上的method1效果和作用在this monitor的method2效果等同。

注意:由于作用的是this monitor,所以该对象在调用method1的时候,this monitor加锁会导致该对象其他争抢该锁的方法进入阻塞(即method1执行过程中会导致method2阻塞,反之亦然)

package com.practice.concurrent.chapter04.sync;

import java.util.concurrent.TimeUnit;

public class ThisMonitor {
    public synchronized void method1(){
        System.out.println(Thread.currentThread().getName()+"enter to method1");
        try {
            TimeUnit.MINUTES.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public void method2(){
        synchronized(this){
            System.out.println(Thread.currentThread().getName()+"enter to method2");
            try {
                TimeUnit.MINUTES.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ThisMonitor thisMonitor = new ThisMonitor();
        new Thread(thisMonitor::method1).start();
        new Thread(thisMonitor::method2).start();
    }
}

2、Class monitor

synchronized关键字直接写在静态方法上的method1效果和作用在ClassMonitor.class的method2效果等同。

注意:如果使用ClassMonitor会导致该类型的所有争抢该锁的方法同时只有一个能够执行(包括同一个类型下的所有对象调用该类方法也会阻塞,同时只有一个运行)

package com.practice.concurrent.chapter04.sync;

import java.util.concurrent.TimeUnit;

public class ClassMonitor {
    public static synchronized void method1(){
        System.out.println(Thread.currentThread().getName()+" enter to method1");
        try {
            TimeUnit.MINUTES.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void method2(){
        synchronized(ClassMonitor.class){
            System.out.println(Thread.currentThread().getName()+" enter to method2");
            try {
                TimeUnit.MINUTES.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new Thread(ClassMonitor::method1).start();
//        new Thread(ClassMonitor::method2).start();
        ClassMonitor classMonitor = new ClassMonitor();
        new Thread(){
            @Override
            public void run() {
                classMonitor.method2();
            }
        }.start();

    }
}

详见 :https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值