【发布时间】:2014-01-21 07:03:23
【问题描述】:
我已经开始学习线程同步了。
同步方式:
public class Counter {
private static int count = 0;
public static synchronized int getCount() {
return count;
}
public synchronized setCount(int count) {
this.count = count;
}
}
同步块:
public class Singleton {
private static volatile Singleton _instance;
public static Singleton getInstance() {
if (_instance == null) {
synchronized(Singleton.class) {
if (_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}
什么时候应该使用synchronized 方法和synchronized 块?
为什么synchronized 块比synchronized 方法更好?
【问题讨论】:
-
在第一种情况下,我将使用 AtomicInteger,在第二种情况下,我将
enum用于 Singleton。 -
哪里说的比较好?您提出问题的依据是什么?
标签: java multithreading synchronization