[英]Is synchronized static method legal in Java?
Java中的同步靜態方法是否合法?
是。 它獲取對象的鎖定,該對象表示定義方法的類(例如,MyClass.class)
是的,它簡化了這樣的靜態工廠方法:
class Foo {
private Foo() {}
public static synchronized Foo getInstance() {
if (instance == null) {
instance = new Foo();
}
return instance;
}
private static Foo instance = null;
}
如果無法synchronized
static
方法,可能會出現以下情況:
class Foo {
private Foo() {}
public static Foo getInstance() {
synchronized (LOCK) {
if (instance == null) {
instance = new Foo();
}
}
return instance;
}
private static Foo instance = null;
private static final Object LOCK = Foo.class;
// alternative: private static final Object LOCK = new Object();
}
這不是什么大不了的事,它只保存了2行代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.