Java——單例模式的static方法和非static方法是否是執行緒安全的?
阿新 • • 發佈:2018-12-24
答案是:單例模式的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