Java同步机制:sychronized对代码影响
作者:duketian 日期:2008-05-20 11:08:26
Java对多线程的支持与同步机制深受大家的喜爱,似乎看起来使用了synchronized关键字就可以轻松地解决多线程共享数据同步问题。到底如何?――还得对synchronized关键字的作用进行深入了解才可定论。
总的说来,synchronized关键字可以作为函数的修饰符,也可作为函数内的语句,也就是平时说的同步方法和同步语句块。如果再细的分类,synchronized可作用于instance变量、object reference(对象引用)、static函数和class literals(类名称字面常量)身上。
在进一步阐述之前,我们需要明确几点:
A.无论synchronized关键字加在方法上还是对象上,它取得的锁都是对象,而不是把一段代码或函数当作锁――而且同步方法很可能还会被其他线程的对象访问。
B.每个对象只有一个锁(lock)与之相关联。
C.实现同步是要很大的系统开销作为代价的,甚至可能造成死锁,所以尽量避免无谓的同步控制。
接着来讨论synchronized用到不同地方对代码产生的影响:
假设P1、P2是同一个类的不同对象,这个类中定义了以下几种情况的同步块或同步方法,P1、P2就都可以调用它们。
1.把synchronized当作函数修饰符时,示例代码如下:
这也就是同步方法,那这时synchronized锁定的是哪个对象呢?它锁定的是调用这个同步方法对象。也就是说,当一个对象P1在不同的线程中执行这个同步方法时,它们之间会形成互斥,达到同步的效果。但是这个对象所属的Class所产生的另一对象P2却可以任意调用这个被加了synchronized关键字的方法。
上边的示例代码等同于如下代码:
(1)处的this指的是什么呢?它指的就是调用这个方法的对象,如P1。可见同步方法实质是将synchronized作用于object reference。――那个拿到了P1对象锁的线程,才可以调用P1的同步方法,而对P2而言,P1这个锁与它毫不相干,程序也可能在这种情形下摆脱同步机制的控制,造成数据混乱
2.同步块,示例代码如下:
这时,锁就是so这个对象,谁拿到这个锁谁就可以运行它所控制的那段代码。当有一个明确的对象作为锁时,就可以这样写程序,但当没有明确的对象作为锁,只是想让一段代码同步时,可以创建一个特殊的instance变量(它得是一个对象)来充当锁:
注:零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码:生成零长度的byte[]对象只需3条操作码,而Object lock = new Object()则需要7行操作码。
3.将synchronized作用于static 函数,示例代码如下:
代码中的methodBBB()方法是把class literal作为锁的情况,它和同步的static函数产生的效果是一样的,取得的锁很特别,是当前调用这个方法的对象所属的类(Class,而不再是由这个Class产生的某个具体对象了)。
记得在《Effective Java》一书中看到过将 Foo.class和 P1.getClass()用于作同步锁还不一样,不能用P1.getClass()来达到锁这个Class的目的。P1指的是由Foo类产生的对象。
可以推断:如果一个类中定义了一个synchronized的static函数A,也定义了一个synchronized 的instance函数B,那么这个类的同一对象Obj在多线程中分别访问A和B两个方法时,不会构成同步,因为它们的锁都不一样。A方法的锁是Obj所属的那个Class,而B的锁是Obj这个对象。
小结:
搞清楚synchronized锁定的是哪个对象,就能帮助我们设计更安全的多线程程序。
还有一些技巧可以让我们对共享资源的同步访问更加安全:
1. 定义private 的instance变量+它的 get方法,而不要定义public/protected的instance变量。如果将变量定义为public,对象在外界可以绕过同步方法的控制而直接取得它,并改动它。这也是JavaBean的标准实现方式之一。
2. 如果instance变量是一个对象,如数组或ArrayList什么的,那上述方法仍然不安全,因为当外界对象通过get方法拿到这个instance对象的引用后,又将其指向另一个对象,那么这个private变量也就变了,岂不是很危险。 这个时候就需要将get方法也加上synchronized同步,并且,只返回这个private对象的clone()――这样,调用端得到的就是对象副本的引用了。
总的说来,synchronized关键字可以作为函数的修饰符,也可作为函数内的语句,也就是平时说的同步方法和同步语句块。如果再细的分类,synchronized可作用于instance变量、object reference(对象引用)、static函数和class literals(类名称字面常量)身上。
在进一步阐述之前,我们需要明确几点:
A.无论synchronized关键字加在方法上还是对象上,它取得的锁都是对象,而不是把一段代码或函数当作锁――而且同步方法很可能还会被其他线程的对象访问。
B.每个对象只有一个锁(lock)与之相关联。
C.实现同步是要很大的系统开销作为代价的,甚至可能造成死锁,所以尽量避免无谓的同步控制。
接着来讨论synchronized用到不同地方对代码产生的影响:
假设P1、P2是同一个类的不同对象,这个类中定义了以下几种情况的同步块或同步方法,P1、P2就都可以调用它们。
1.把synchronized当作函数修饰符时,示例代码如下:
1 |
Public synchronized void methodAAA()
{
//….
}
|
这也就是同步方法,那这时synchronized锁定的是哪个对象呢?它锁定的是调用这个同步方法对象。也就是说,当一个对象P1在不同的线程中执行这个同步方法时,它们之间会形成互斥,达到同步的效果。但是这个对象所属的Class所产生的另一对象P2却可以任意调用这个被加了synchronized关键字的方法。
上边的示例代码等同于如下代码:
1 | public void methodAAA()
{
synchronized (this) // (1)
{
//…..
}
}
|
(1)处的this指的是什么呢?它指的就是调用这个方法的对象,如P1。可见同步方法实质是将synchronized作用于object reference。――那个拿到了P1对象锁的线程,才可以调用P1的同步方法,而对P2而言,P1这个锁与它毫不相干,程序也可能在这种情形下摆脱同步机制的控制,造成数据混乱
2.同步块,示例代码如下:
1 | public void method3(SomeObject so)
{
synchronized(so)
{
//…..
}
}
|
这时,锁就是so这个对象,谁拿到这个锁谁就可以运行它所控制的那段代码。当有一个明确的对象作为锁时,就可以这样写程序,但当没有明确的对象作为锁,只是想让一段代码同步时,可以创建一个特殊的instance变量(它得是一个对象)来充当锁:
1 | class Foo implements Runnable
{
private byte[] lock = new byte[0]; // 特殊的instance变量
Public void methodA()
{
synchronized(lock) { //… }
}
//…..
}
|
注:零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码:生成零长度的byte[]对象只需3条操作码,而Object lock = new Object()则需要7行操作码。
3.将synchronized作用于static 函数,示例代码如下:
1 | Class Foo
{
public synchronized static void methodAAA() // 同步的static 函数
{
//….
}
public void methodBBB()
{
synchronized(Foo.class) // class literal(类名称字面常量)
}
}
|
代码中的methodBBB()方法是把class literal作为锁的情况,它和同步的static函数产生的效果是一样的,取得的锁很特别,是当前调用这个方法的对象所属的类(Class,而不再是由这个Class产生的某个具体对象了)。
记得在《Effective Java》一书中看到过将 Foo.class和 P1.getClass()用于作同步锁还不一样,不能用P1.getClass()来达到锁这个Class的目的。P1指的是由Foo类产生的对象。
可以推断:如果一个类中定义了一个synchronized的static函数A,也定义了一个synchronized 的instance函数B,那么这个类的同一对象Obj在多线程中分别访问A和B两个方法时,不会构成同步,因为它们的锁都不一样。A方法的锁是Obj所属的那个Class,而B的锁是Obj这个对象。
小结:
搞清楚synchronized锁定的是哪个对象,就能帮助我们设计更安全的多线程程序。
还有一些技巧可以让我们对共享资源的同步访问更加安全:
1. 定义private 的instance变量+它的 get方法,而不要定义public/protected的instance变量。如果将变量定义为public,对象在外界可以绕过同步方法的控制而直接取得它,并改动它。这也是JavaBean的标准实现方式之一。
2. 如果instance变量是一个对象,如数组或ArrayList什么的,那上述方法仍然不安全,因为当外界对象通过get方法拿到这个instance对象的引用后,又将其指向另一个对象,那么这个private变量也就变了,岂不是很危险。 这个时候就需要将get方法也加上synchronized同步,并且,只返回这个private对象的clone()――这样,调用端得到的就是对象副本的引用了。
平均得分
(0 次评分)
评论: 9 | 查看次数: 571
- 共有 9 条评论
- 共有 9 条评论
发表评论
订阅
上一篇
|

文章来自:
标签: 
balance . mp3 mp4 player plays a part in the outcome . mp3 mp4 player of combat, gear is a major differentiator that makes up for shortcomings in other areas. mp3 mp4 player In fact, with . mp3 player kaufen the introduction of Resilience, gear more than mp4 ever plays a more substantial part in PvP. power level In an Arena match, the very first thing we . power level scope out is gear. wow level Through quick tab-selection viewing .wow leveling of character portraits, we generally wow lvl have a good idea of the classes we're up against if they keep their helm graphic on. wow lvl If they are wearing Season 3 shoulders, then we know . wow lvl 60 their relative experience. wow lvl 70 This is why the visual i.wow power leveling mpact of Arena shoulders is so important.wow powerlevel It immediately gives you a general idea of how tough the match will be. wow powerlevel Players in full S3 will likely have over 10k hp and over. wow powerleveling 400 Resilience, depending on the class and spec. A full S3 SL/SL Warlock, for example, will easily have. about 12-13k hp and over 400 Resilience. Identifying weapons is slightly more . difficult but will also give a general idea of an enemy's strength. Season 1 and 2 weapons share the same graphics, so it's harder to identify. Season 3 weapons, on the other hand, are distinctive and share models with Black Temple and Mount Hyjal weapons. which 最新免费网络游戏 have relatively the same power. A review of Brutal Gladiator weapons will come in handy because these will be the most common way to identify opponents of relative skill. With the new mechanics. in place for Arenas, Season 4 will more or less weed out the chaff from the grain.
4GB MP3 PLAYER My wife is a shrewd little fox. Bluetooth Headset She knows just how much I love the fact. Bluetooth Headsets that she plays the game with me so sometimes, when we have our little domestic arguments, she makes sure. cell phone accessories to cancel her WoW account just to drive home a point. des po wow Of course, it doesn't mean much since we're both paid up for the next few months, but the message is clear -- "we make up (or you see things my way). digital camcorder or I'm quitting the game!" Of course, we don't reconcile merely because I'll be losing my . digital camcorders favorite playing partner, but I have to confess that it doesn't make . dvd players me happy one bit. free online games For parents, World of Warcraft can be a . free online war games useful bargaining chip for their kids with the parental . gold wow controls feature. gold wow It's easy enough to control WoW time if kids aren't doing their homework, floundering in school, or simply not. mp3 mp4 player doing their chores. mp3 player Conversely, a friend . mp3 player accessories of mine gave his son a WoW subscription when . mp3 player accessory he did well in school. mp3 player kaufen World of Warcraft can be so. online games much fun and addicting that it's . play war games often used as a social tool, and it's often upsetting when our. po wow friends quit playing the game. portable dvd player How many of us have . wow europe had friends whose significant others have "allowed" them to. wow geld play the game after, say, a wonderful date. wow gold verkaufen I'm not sure if it only applies to me, but . wow level service because I play the game with many of my RL friends . wow leveling service and my family, I use the lure of WoW . to full effect. I once had my brother do a specific task for . the promise of an upgrade to The Burning Crusade. A little before he finished what I asked him to do, I secretly upgraded his account. so he could免费网络游戏 finally make his Blood Elf Priest. Kind of manipulative, I know, but we did end up having . a lot of fun leveling our alts together. How about you. How much a part of your life is WoW and has it .最新网游 ever been used as a bargaining . chip in your social life.
Warhammer Gold
Warhammer Online Gold
Warhammer Accounts
Warhammer Power Leveling
Warhammer Online Key
Warhammer Gold
Warhammer Online Gold
Warhammer Time Card
Warhammer CD Key
WAR gold
warhammer online gold
Buy WAR gold
Buy warhammer gold
Buy warhammer online gold
warhammer gold
WAR Accounts
warhammer Accounts
warhammer online Accounts
Buy WAR Accounts
warhammer Accounts for sale
Warhammer Power Leveling
Warhammer Online Power Leveling
War Power Leveling
Buy Warhammer Power Leveling
Warhammer PowerLeveling
Cheap Warhammer Power Leveling
Cheap Warhammer Online Power Leveling
Buy War Power Leveling
Warhammer EU Power Leveling
Cheap Warhammer Gold
Cheap Warhammer online gold
Buy Cheap Warhammer Gold
Buy WAR Gold
Warhammer EU Gold
Warhammer EU Power Leveling
Warhammer EU CD Key
Warhammer EU Accounts
Warhammer CD Key
Warhammer online CD Key
Warhammer Timecard
Buy Warhammer Time Card
Warhammer 60 days Time Card
Cheap WAR Accounts
Cheap warhammer Accounts
Cheap warhammer online Accounts
Buy Cheap WAR Accounts
buy Warhammer CD Key
buy Warhammer online CD Key
cheap Warhammer CD key
warhammer time card
Warhammer prepaid time card
Buy Lotro Gold | Lord Of The Rings Online Gold
Lotro Accounts
| Buy Lotro Accounts
Lord Of The Rings Online Power Leveling | Lord Of The Rings Online PowerLeveling
Lotro Cd Key | Lord Time Card
Lotro Gold | Lotro Gold Instant Delivery
lord of the rings online accounts | lord of the rings online accounts for sale
Lotro Power Leveling | Lotro Powerleveling
Lord Of The Rings Online Cd Key | Lord Of The Rings Online Time Card
Lord of the Rings Online Gold
Buy Lotro Gold
Sell LoTRO Gold
LoTRO CD Key
LoTRO Europe Gold
Cheap LoTRO Accounts
Lord of the Rings Online Power Leveling
Lord of the Rings online CD Key
Cheap Lotro Gold
窃听器
手机监听器
监听器
手机窃听器
窃听器
手机监听器
监听器
手机窃听器
窃听器
手机监听器
监听器
手机窃听器│窃听器
手机窃听器│窃听器
手机窃听器│窃听器
手机窃听器│窃听器
手机窃听器│窃听器
手机窃听器│窃听器
手机窃听器│窃听器
手机窃听器│窃听器
手机窃听器│窃听器
手机窃听器│窃听器
手机窃听器│窃听器
手机窃听器│窃听器
Cheap Warhammer gold
Warhammer Online gold
WAR Gold
Buy Warhammer Gold
Warhammer Online Gold
Warhammer Gold for sale
Warhammer Accounts
Buy Warhammer Accounts
Cheap Warhammer Accounts
Warhammer Power leveling
WAR Power leveling
Warhammer Online Power Leveling
Warhammer CD Key
WAR CD Key
Warhammer Online CD Key
Warhammer Game Time Card
Cheap Warhammer gold
Warhammer Online gold
WAR Gold
Buy Warhammer Gold
Warhammer Online Gold
Warhammer Gold for sale
Warhammer Accounts
Buy Warhammer Accounts
Cheap Warhammer Accounts
Warhammer Power leveling
WAR Power leveling
Warhammer Online Power Leveling
Warhammer CD Key
WAR CD Key
Warhammer Online CD Key
Warhammer Game Time Card
Cheap Warhammer gold
Warhammer Online gold
WAR Gold
Buy Warhammer Gold
Warhammer Online Gold
Warhammer Gold for sale
Warhammer Accounts
Buy Warhammer Accounts
Cheap Warhammer Accounts
Warhammer Power leveling
WAR Power leveling
Warhammer Online Power Leveling
Warhammer CD Key
WAR CD Key
Warhammer Online CD Key
Warhammer Game Time Card