同步方法和块之间有什么区别? [英] What is the difference between synchronized methods and blocks?

查看:103
本文介绍了同步方法和块之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

synchronized 方法synchronized 声明之间有什么区别?

What is the difference between synchronized methods and synchronized statements?

如果可能的话,请使用示例使其更清楚.

If possible, please use an example to make it more clear.

推荐答案

同步方法锁定与该类的实例(即"this")或该类(如果是静态方法)关联的监视器,并阻止其他人执行因此,直到从方法返回为止.同步块可以锁定任何监视器(告诉您哪个监视器),并且其作用域可以小于encolsing方法的作用域.

A synchronized method locks the monitor associated with the instance of the class (ie 'this') or the class (if a static method) and prevents others from doing so until the return from the method. A synchronized block can lock any monitor (you tell it which) and can have a scope smaller than that of the encolsing method.

如果同步块最终不等同于方法的整个范围,并且/或者如果它们锁定的东西比实例(或类,如果不是静态的)那么严酷,则首选同步块.

Synchronized blocks are prefered if they don't end up equivalent to the entire scope of the method and/or if they lock something less draconian than the instance (or class if static).

这篇关于同步方法和块之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆