您的位置:首页 > 编程语言 > Java开发

Java——单例模式的static方法和非static方法是否是线程安全的?

2018-03-01 23:45 399 查看
      答案是:单例模式的static方法和非static方法是否是线程安全的,与单例模式无关。也就说,如果static方法或者非static方法不是线程安全的,那么不会因为这个类使用了单例模式,而变的安全。  闲话休说,看代码:import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestSingleton {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(10);
for (int j = 0; j < 100000; j++) {
pool.submit(new Thread() {
public void run() {

Singleton.get().add();
}
});
}
pool.shutdownNow();
while (!pool.isTerminated())
;
System.out.println(Singleton.get().getcnt());
}
}

class Singleton {
private static Singleton singleton = new Singleton();

int cnt = 0;

private Singleton() {}

public static Singleton get() {
return singleton;
}

public void add() {
cnt++;
}

public int getcnt() {
return cnt;
}
}
参考链接(个人博客):  http://www.cnblogs.com/liu-qing/p/4469965.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息