Java synchronized (this) 的含义
2016-04-18 17:10
567 查看
Synchronized Methods 和 Synchronized Statements的区别在于,前者自动帮你锁了当前调用方法的对象实例(若Static方法则锁类对象)。
Locks In Synchronized Methods
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns.
The lock release occurs even if the return was caused by an uncaught exception.
当线程调用一个synchronized method时,它将自动获取该方法的对象上的intrinsic lock,并在方法返回时候释放,即使是方法返回是由于非捕获的异常,锁也会被释放。
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.
你或许在想当一个静态的synchronized method被调用时,会发生什么,因为一个静态方法关联的是一个类而不是对象?在这种情况,
该线程将获取这个类关联的Class对象里面的intrinsic lock。所以控制访问类静态字段的锁是不同于控制类实例的锁的
Synchronized Statements
Another way to create synchronized code is with synchronized statements. Unlike synchronized methods,
synchronized statements must specify the object that provides the intrinsic lock:
另外一个构建同步代码的方法是使用synchronized statements。不像synchronized methods,synchronized statements必须指定提供intrinsic lock的对象。
Locks In Synchronized Methods
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns.
The lock release occurs even if the return was caused by an uncaught exception.
当线程调用一个synchronized method时,它将自动获取该方法的对象上的intrinsic lock,并在方法返回时候释放,即使是方法返回是由于非捕获的异常,锁也会被释放。
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.
你或许在想当一个静态的synchronized method被调用时,会发生什么,因为一个静态方法关联的是一个类而不是对象?在这种情况,
该线程将获取这个类关联的Class对象里面的intrinsic lock。所以控制访问类静态字段的锁是不同于控制类实例的锁的
Synchronized Statements
Another way to create synchronized code is with synchronized statements. Unlike synchronized methods,
synchronized statements must specify the object that provides the intrinsic lock:
另外一个构建同步代码的方法是使用synchronized statements。不像synchronized methods,synchronized statements必须指定提供intrinsic lock的对象。
public void addName(String name) { synchronized(this) { lastName = name; nameCount++; } nameList.add(name); }
相关文章推荐
- Reflect Java反射机制
- VisualVM连接远程Java进程
- java学习笔记(一)
- java学习 集合之LinkedList
- Java内部类
- java线程池学习
- Spring基于 Annotation 的简单介绍
- JAVA知识汇总链接
- JAVA设计模式之工厂模式
- Myeclipse的破解码
- Java异常处理(try、catch、finally使用)
- 测试java jdk 支持最大内存
- eclipse插件开发获取Eclipse相关的文件根目录
- Java ThreadPoolExecutor详解
- Java多线程(6) 线程池
- java8新特性(2)-Stream
- Java IO流
- MyEclipse内存溢出问题解决方法
- Java实现敏感词过滤
- java设计模式【策略模式】