我有一个类,所有方法都需要同步(没有静态方法)。其中一种方法将每 50 毫秒调用一次。
我想知道将同步关键字放在哪里具有最短的执行时间?
即下面详述的关于执行时间的两个选项之间有什么区别吗?
选项 1(同步方法)
public class MyNativeObject{
private boolean released = false;
public synchronized String read(){
if(released) return null;
return Read();
}
public synchronized void release(){
if(released) return;
released = true;
Release();
}
private native String Read();
private native void Release();
}
选项 2(同步块)
public class MyNativeObject{
private Boolean released = false;
public String read(){
synchronized(released){
if(released) return null;
return Read();
}
}
public void release(){
synchronized(released){
if(released) return;
released = true;
Release();
}
}
private native String Read();
private native void Release();
}