synchronized块的语法如下:
public
void
method()
{
… …
synchronized (表达式)
{
… …
}
}
{
… …
synchronized (表达式)
{
… …
}
}
一、非静态类方法的同步
从《使用Synchronized关键字同步类方法》一文中我们知道使用synchronized关键字来定义方法就会锁定类中所有使用synchronzied关键字定义的静态方法或非静态方法,但这并不好理解。而如果使用synchronized块来达到同样的效果,就不难理解为什么会产生这种效果了。如果想使用synchronized块来锁定类中所有的同步非静态方法,需要使用this做为synchronized块的参数传入synchronized块国,代码如下:
通过synchronized块同步非静态方法
001
public
class
SyncBlock
002 {
003 public void method1()
004 {
005 synchronized ( this ) // 相当于对method1方法使用synchronized关键字
006 {
007 … …
008 }
009 }
010 public void method2()
011 {
012 synchronized ( this ) // 相当于对method2方法使用synchronized关键字
013 {
014 … …
015 }
016 }
017<
002 {
003 public void method1()
004 {
005 synchronized ( this ) // 相当于对method1方法使用synchronized关键字
006 {
007 … …
008 }
009 }
010 public void method2()
011 {
012 synchronized ( this ) // 相当于对method2方法使用synchronized关键字
013 {
014 … …
015 }
016 }
017<