同步方法和静态同步方法

同步方法和静态同步方法

You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from(不同于) the lock for any instance of the class.

Java中的每一个对象都可以作为锁

  • 对于同步方法,锁是当前实例对象。

  • 对于静态同步方法,锁是当前对象的Class对象。

  • 对于同步方法块,锁是synchonized括号里配置的对象。

当一个线程试图访问同步代码块时,它首先必须得到锁,退出或抛出异常时必须释放锁。如下代码,

package com.usoft;

/**
 * If the method is an instance method,
 * it locks the monitor associated with the instance for which it was invoked
 * (that is, the object that will be known as this during execution of the body of the method).
 * If the method is static, it locks the monitor associated with the Class object
 * that represents the class in which the method is defined.
 * Created by liyanxin on 2015/1/5.
 */
public class HelloWorld {

    //静态方法加锁实际上是加在HelloWorld.class上
    synchronized public static void methodA1() {
    }

    //加锁的范围与methodA1一致
    public static void methodA2() {
        synchronized (HelloWorld.class) {
        }
    }

    //修饰在类方法上得锁,实际上是加在当前对象上也就是this
    synchronized public void methodB1() {
    }

    //加锁的范围与methodB1一致
    public void methodB2() {
        synchronized (this) {
        }
    }
}

==========END==========

转载于:https://my.oschina.net/xinxingegeya/blog/345906

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值