以下是《thinking in java》中的一段代码 我不大明白 请各位指教执行ds.g();后 main线程sleep 可是执行ds.f()时不是没有对象锁吗 为什么还能执行呢
import com.bruceeckel.simpletest.*;
class DualSynch {
private Object syncObject = new Object();
public synchronized void f() {
System.out.println("Inside f()");
// Doesn't release lock:
try {
Thread.sleep(500);
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Leaving f()");
}
public void g() {
synchronized(syncObject) {
System.out.println("Inside g()");
try {
Thread.sleep(500);
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Leaving g()");
}
}
}
public class SyncObject {
private static Test monitor = new Test();
public static void main(String[] args) {
final DualSynch ds = new DualSynch();
new Thread() {
public void run() {
ds.f();
}
}.start();
ds.g();
monitor.expect(new String[] {
"Inside g()",
"Inside f()",
"Leaving g()",
"Leaving f()"
}, Test.WAIT + Test.IGNORE_ORDER);
}
}
import com.bruceeckel.simpletest.*;
class DualSynch {
private Object syncObject = new Object();
public synchronized void f() {
System.out.println("Inside f()");
// Doesn't release lock:
try {
Thread.sleep(500);
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Leaving f()");
}
public void g() {
synchronized(syncObject) {
System.out.println("Inside g()");
try {
Thread.sleep(500);
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("Leaving g()");
}
}
}
public class SyncObject {
private static Test monitor = new Test();
public static void main(String[] args) {
final DualSynch ds = new DualSynch();
new Thread() {
public void run() {
ds.f();
}
}.start();
ds.g();
monitor.expect(new String[] {
"Inside g()",
"Inside f()",
"Leaving g()",
"Leaving f()"
}, Test.WAIT + Test.IGNORE_ORDER);
}
}
这个不是也是吗
这个效果跟锁住对象是一样的吧
public synchronized void f() public void g()前者在声明的时候就已经声明了这个方法是synchronized的,而后者没有声明.
但是synchronized的用法是怎么样的呢?
在方法声明的时候把它声明成synchronized 的,那么这个方法就是synchronized 的方法,其方法体也就是synchronized .如果方法没有被声明成synchronized 的,而是方法体的某段代码需要锁定,那就需要把需要锁定的这段代码放入synchronized 块里面,这个时候的声明表达成synchronized(Object obj){……//这里写入需要锁定的代码段}所以,synchronized代码块和synchronized方法是两个不同的概念,声明方法也不一样,synchronized代码块需要传入一个对象锁,而synchronized方法只需方法声明的时候声明成synchronized 就可以了,明白了没???
public void f() {
synchronized(this){
。。
}
}
是一样的。f()g() 所的对象不一样。两个不冲突。
synchronized(xxx){}代码块: 锁的是xxx!