单例模式创建,发令枪压测
代码
单例代码
private static Demo instance = null;
private Demo() {
}
public static Demo getInstance() {
if (instance == null) {
instance = new Demo();
}
return instance;
}
测试代码
public class CountDownLatchTest {
private static final int N = 10;
public static void main(String[] args) throws InterruptedException {
CountDownLatch doneSignal = new CountDownLatch(N);
Executor service = Executors.newCachedThreadPool();
for (int i = 0; i < N; ++i) // create and start threads
service.execute(new WorkerRunnable(doneSignal, i));
doneSignal.await(); // wait for all to finish
}
}
class WorkerRunnable implements Runnable {
private final CountDownLatch doneSignal;
private final int i;
WorkerRunnable(CountDownLatch doneSignal, int i) {
this.doneSignal = doneSignal;
this.i = i;
}
public void run() {
doWork(i);
doneSignal.countDown();
}
void doWork(int i) {
System.out.println(i + "--->"+ Demo.getInstance());
}
}
结果代码(多试几次一定会出现、一次可能不会出现)
0--->com.Demo@46fc9e82
1--->com.Demo@54794585
2--->com.Demo@46fc9e82
3--->com.Demo@46fc9e82
4--->com.Demo@46fc9e82
6--->com.Demo@46fc9e82
7--->com.Demo@46fc9e82
8--->com.Demo@46fc9e82
5--->com.Demo@46fc9e82
9--->com.Demo@46fc9e82
问题1:通过并发创建对象
单例增加 getInstance() 方法上增加 synchronized
问题2:通过序列化进行对象创建
需要对象实现序列化接口才可测试
// 序列化测试
Demo demo = Demo.getInstance();
System.out.println("序列化测试:" + SerializeUtil.unserialize(SerializeUtil.serialize(demo)));
问题3:通过反射进行对象创建
反射对象是
9--->com.jfun365.common.service.promotion.impl.Demo@2d58251c
com.jfun365.common.service.promotion.impl.Demo@3c0a50da