当前位置: 技术问答>java相关
关于《java认证考试指南》中synchronized的一个问题,我写了一段代码却编译不过 :-(
来源: 互联网 发布时间:2015-04-20
本文导语: public class A{ synchronized{ System.out.println("it is free-floating block"); } } 编译时却给出如下提示: A.java:2: Type expected. synchronized{ ^ 但是在《java认证考试指南》P72...
public class A{
synchronized{
System.out.println("it is free-floating block");
}
}
编译时却给出如下提示:
A.java:2: Type expected.
synchronized{
^
但是在《java认证考试指南》P72页的表中写明了synchronized可以修饰free-floating block的呀!
那位知道为什么?
synchronized{
System.out.println("it is free-floating block");
}
}
编译时却给出如下提示:
A.java:2: Type expected.
synchronized{
^
但是在《java认证考试指南》P72页的表中写明了synchronized可以修饰free-floating block的呀!
那位知道为什么?
|
可能是要加上:synchronized(this){...}
|
你的用法不对!
To synchronize an entire method, using the lock of the object that
owns the method. To do this, put the synchronized keyword in the
method’s declaration.
To synchronize part of a method, using the lock of an arbitrary object. Put curly brackets around the code to be synchronized, preceded by synchronized(theArbitraryObject).
To synchronize part of a method, using the lock of the object that
owns the method. Put curly brackets around the code to be synchronized, preceded by synchronized(this).
To synchronize an entire method, using the lock of the object that
owns the method. To do this, put the synchronized keyword in the
method’s declaration.
To synchronize part of a method, using the lock of an arbitrary object. Put curly brackets around the code to be synchronized, preceded by synchronized(theArbitraryObject).
To synchronize part of a method, using the lock of the object that
owns the method. Put curly brackets around the code to be synchronized, preceded by synchronized(this).
|
synchronized有两类用法,一类用于同步整个方法,一类同步对象。事实上,
同步机制的实质锁。synchronized method()(同步方法)表示每次只能有一个
线程可以访问该方法,synchronized (object)(同步对象)表示每次只能有一
个线程可以访问该对象。你的用法中,需要在synchronized修饰符后带上对象
或方法名。
同步机制的实质锁。synchronized method()(同步方法)表示每次只能有一个
线程可以访问该方法,synchronized (object)(同步对象)表示每次只能有一
个线程可以访问该对象。你的用法中,需要在synchronized修饰符后带上对象
或方法名。
|
它是可以修饰 Free-Floating Block,但是你要告诉它你要锁定什么啊。
synchronized(this){ //..this is a Free-Floating Block
}
至于修饰 method 就不用了。
synchronized(this){ //..this is a Free-Floating Block
}
至于修饰 method 就不用了。
|
你要声明要对哪个对象进行同步:synchronized(this)