0%

Java设计模式

单例模式

1
2
3
4
5
6
7
public class Singleton {
private Singleton() {}
private static Singleton instance = new Singleton();
public static void getInstance() {
return this.instance;
}
}

更好的解法

1
2
3
4
5
6
7
8
9
public class Singleton {
private Singleton(){}
private static class testHolder{
private static Singleton intance = new Singleton();
}
public static Singleton getIntance() {
return testHolder.intance;
}
}

i++线程同步

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Test implements Runnable {
// private static AtomicInteger atomicInteger = new AtomicInteger(0);
// private void increase() {
// atomicInteger.incrementAndGet();
// }

public static int n = 0;
//如果是static 则给类加锁,没有static则给方法加锁。
public static synchronized void increase() {
n++;
}
@Override
public void run() {
for (int i = 0; i < 100000; i++) {
increase();
}
}

public static void main(String[] args) throws InterruptedException {
//给类加锁则可以实现2个实例并行安全
//给方法加锁只能实现单个实例的线程安全
Test test = new Test();
Thread thread1 = new Thread(new Test());
Thread thread2 = new Thread(new Test());

thread1.start();
thread2.start();
thread1.join();
thread2.join();

System.out.println(n);
}

不变模式

final 修饰变量

1
2
3
4
5
6
7
8
9
10
11
public final class product {
private final String no;

public Product(String no) {
super();
this.num = num;
}
public int getNum() {
return num;
}
}

生产者消费者模型

  • blockQueue(加阻塞锁)
  • disruptor(环形队列,CAS实现无锁操作)

future 模型

  • 异步调用。如果函数执行的慢,让被调用者立即返回,后台慢慢处理。
  • 充分利用等待时间