package com.jva.util.design.single;
/**
* 饱汉模式
*
* @author chengpingjia
* @since 2023/4/26 11:41
*/
public class Full {
private static final Full single = new Full();
private Full() {
}
private static Full getSingle() {
return single;
}
}
2.1饿汉模式
package com.jva.util.design.single;
import cn.hutool.core.collection.ConcurrentHashSet;
import java.util.Set;
import java.util.concurrent.*;
import java.util.stream.IntStream;
/**
* 饿汉模式
*
* @author chou
* @since 2023/4/26 11:41
*/
public class Hunger {
private static Hunger single = null;
/**
* 私有构造方法避免实例化
*/
private Hunger() {
}
/**
* 饿汉模式在使用的时候再去创建对象
* 问题:在并发情况下可能有创建多个对象的可能
*
* @return
*/
private static Hunger getSingle() {
if (single == null) {
single = new Hunger();
}
return single;
}
/**
* 通过添加sync解决并发情况下创建多个对象的问题
* 问题: sync包住了创建代码,效率比较低
*
* @return
*/
private static synchronized Hunger getSingle2() {
if (single == null) {
single = new Hunger();
}
return single;
}
/**
* 通过添加sync解决并发情况下创建多个对象的问题
* 问题: sync包住了创建代码,效率比较低
*
* @return
*/
private static Hunger getSingle3() {
if (single == null) {
synchronized (Hunger.class){
if (single == null) {
single = new Hunger();
}
}
}
return single;
}
public static void main(String[] args) throws Exception {
// ThreadPoolExecutor threadPoolExecutor = ThreadUtil.newExecutor(50, 10);
Set<Integer> hashSet = new ConcurrentHashSet<>();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(50, 100, 2L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
int size = 100;
CountDownLatch countDownLatch = new CountDownLatch(size);
IntStream.range(0,size).forEach(i->{
Future<Integer> future = threadPoolExecutor.submit(() -> {
try {
int hashCode = Hunger.getSingle().hashCode();
int hashCode2 = Hunger.getSingle2().hashCode();
int hashCode3 = Hunger.getSingle3().hashCode();
hashSet.add(hashCode3);
return hashCode;
} finally {
countDownLatch.countDown();
}
});
});
countDownLatch.await();
// 等待线程执行完成
hashSet.forEach(System.out::println);
}
}