文章目录
- 8. 手撕设计模式
- 8.1 手撕单例模式
- 8.1.1 懒汉式线程不安全
- 8.1.2 懒汉式线程安全
- 8.1.3 双重检验
- 8.1.4 饿汉式
- 8.2 手撕生产者消费者模式
- 8.3 手撕工厂模式
8. 手撕设计模式
8.1 手撕单例模式
- 单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
8.1.1 懒汉式线程不安全
- 懒汉式单例模式 只是声明对象,等到调用getInstanc()的时候才进行new 对象 因为他懒
class lazyUnsafe {
private static lazyUnsafe lazyUnsafe;
private lazyUnsafe(){
System.out.println(Thread.currentThread().getName());
}
public static lazyUnsafe getInstance() {
if (lazyUnsafe == null) {
lazyUnsafe = new lazyUnsafe();
}
return lazyUnsafe;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread( ()->{
lazyUnsafe.getInstance();
}
).start();
}
}
8.1.2 懒汉式线程安全
class lazysafe {
private static lazySafe lazysafe;
private lazySafe(){
System.out.println(Thread.currentThread().getName());
}
public static synchronized lazySafe getInstance() {
if (lazysafe == null) {
lazysafe = new lazySafe();
}
return lazyUnsafe;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread( ()-> {
lazySafe.getInstance();
}).start();
}
}
}
}
8.1.3 双重检验
- 第一个if语句,用来确认调用getInstance()时instance是否为空,如果不为空即已经创建,则直接返回,如果为空,那么就需要创建实例,于是进入synchronized同步块。
- synchronized加类锁,确保同时只有一个线程能进入,进入以后进行第二次判断,是因为对于首个拿锁者,它的时段instance肯定为null,那么进入new Singleton()对象创建,在首个拿锁者的创建对象期间,可能有其他线程同步调用getInstance(),那么它们也会通过if进入到同步块试图拿锁然后阻塞(因为这时首拿锁的线程还在创建对象期间)。
- 这样的话,当首个拿锁者完成了对象创建,之后的线程都不会通过第一个if了,而这期间阻塞的线程开始唤醒,它们则需要靠第二个if语句来避免再次创建对象。
- 以上就是双检索的实现思路,synchronized与第二个if即是用来保证线程安全与不产生第二个实例
public class SingleLazyDCL {
private volatile static SingleLazyDCL singleLazyDCL;
private SingleLazyDCL (){
System.out.println(Thread.currentThread().getName());
}
public static SingleLazyDCL getInstance() {
if (singleLazyDCL == null) {
synchronized (SingleLazyDCL.class) {
if (singleLazyDCL == null) {
singleLazyDCL = new SingleLazyDCL();
}
}
}
return singleLazyDCL;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread( ()->{
SingleLazyDCL.getInstance();
}).start();
}
}
}
8.1.4 饿汉式
public class SingleHungry {
private static SingleHungry singleHungry = new SingleHungry();
private SingleHungry(){
System.out.println(Thread.currentThread().getName());
}
public static SingleHungry getInstance() {
return singleHungry;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread( ()->{
SingleHungry.getInstance();
}).start();
}
}
}
8.2 手撕生产者消费者模式
- 生产者消费者问题是一个多线程同步的经典问题,这个问题描述了生产者线程和消费者线程共享固定大小的缓冲区的问题。生产者不断的向缓冲区添加数据,消费者不断的消费缓冲区的数据,这个问题的关键是:
- 保证生产者在缓冲区满的时候不再向缓冲区添加数据,消费者在缓冲区空的时候也不会的时候消费缓冲区数据
- 解决思路:
- 生产者不断的生产,直到缓冲区满的时候,阻塞生产者线程,缓冲区不满的时候,继续生产
- 消费者不断的消费,直到缓冲区空的时候,阻塞消费者线程,缓冲区不空的时候,继续消费
public class ProducerAndConsumer {
static class Consumer implements Runnable {
private List<Integer> queue;
public Consumer(List<Integer> queue) {
this.queue = queue;
}
@Override
public void run() {
try {
while (true) {
synchronized (queue) {
while (queue.isEmpty()) {
System.out.println("Queue is Empty");
queue.wait();
}
int i = queue.remove(0);
queue.notifyAll();
System.out.println(Thread.currentThread().getName() + "消费了:" + i + "还剩:" + queue.size());
Thread.sleep(100);
}
}
} catch (InterruptedException e) {
}
}
}
static class Producer implements Runnable {
private List<Integer> queue;
private int length;
public Producer(List<Integer> queue, int length) {
this.queue = queue;
this.length = length;
}
@Override
public void run() {
try {
while (true) {
synchronized (queue) {
while (queue.size() > length) {
queue.wait();
}
queue.add(1);
System.out.println(Thread.currentThread().getName() + "生产了" + 1 + "现在有" + queue.size());
Thread.sleep(100);
queue.notifyAll();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
List<Integer> queue = new ArrayList<>();
int length = 10;
ExecutorService service = Executors.newCachedThreadPool();
service.execute(new Producer(queue, 10));
service.execute(new Producer(queue, 10));
service.execute(new Producer(queue, 10));
service.execute(new Consumer(queue));
service.execute(new Consumer(queue));
service.execute(new Consumer(queue));
}
}
8.3 手撕工厂模式
- 在实际业务中我们经常创建对象,常用的做法就是new。但是有些情况下对new不做控制就会造成资源浪费,不能做到多路复用,而且很容易达到系统瓶颈。这个时候就可以考虑使用工厂模式。比如数据库连接资源,Redis连接资源、日志记录等场景。
public interface Computer {
Computer make();
}
public class Laptop implements Computer {
public Laptop() {
System.out.println("make a Laptop Computer!");
}
@Override
public Computer make() {
return new Laptop();
}
}
public class Desktop implements Computer {
public Desktop() {
System.out.println("make a Desktop Computer!");;
}
@Override
public Desktop make() {
return new Desktop();
}
}
public class ComputerSimpleFactory {
Computer makeComputer(String computerType) {
switch (computerType) {
case "desktop":
return new Desktop();
case "laptop":
return new Laptop();
}
return null;
}
public static void main(String[] args) {
ComputerSimpleFactory computerSimpleFactory = new ComputerSimpleFactory();
Computer desktop = computerSimpleFactory.makeComputer("desktop");
Computer laptop = computerSimpleFactory.makeComputer("laptop");
}
}