精通Java

1. 概述

1.1 Java的重要性

Java是一门面向对象的编程语言,具有跨平台、安全性高、生态丰富等特点,是企业级应用开发的主流语言。

本文内容

  • Java基础:语言特性、语法基础
  • 面向对象:封装、继承、多态
  • 集合框架:List、Set、Map等集合
  • 并发编程:多线程、线程池、并发工具
  • JVM原理:内存模型、垃圾回收、性能调优
  • 设计模式:常用设计模式实战
  • 框架使用:Spring、MyBatis等框架
  • 性能优化:Java性能优化技巧

1.2 本文内容结构

本文将从以下几个方面深入探讨如何精通Java:

  1. Java基础:语言特性和语法
  2. 面向对象编程:OOP核心概念
  3. 集合框架:常用集合的使用
  4. 并发编程:多线程和并发处理
  5. JVM原理:Java虚拟机深入理解
  6. 设计模式:常用设计模式实战
  7. 框架应用:主流框架的使用
  8. 性能优化:Java性能优化技巧

2. Java基础

2.1 Java语言特性

2.1.1 核心特性

Java核心特性

  1. 面向对象:封装、继承、多态
  2. 平台无关性:一次编写,到处运行
  3. 自动内存管理:垃圾回收机制
  4. 多线程支持:内置多线程支持
  5. 安全性:沙箱机制,安全性高

示例代码

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 JavaFeatures {

// 1. 面向对象:类和对象
private String name;
private int age;

// 2. 封装:getter和setter
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

// 3. 多线程支持
public void multiThreadExample() {
Thread thread = new Thread(() -> {
System.out.println("Thread running");
});
thread.start();
}

// 4. 异常处理
public void exceptionExample() {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}

2.2 数据类型

2.2.1 基本数据类型

Java基本数据类型

类型 大小 范围 默认值
byte 1字节 -128 ~ 127 0
short 2字节 -32768 ~ 32767 0
int 4字节 -2^31 ~ 2^31-1 0
long 8字节 -2^63 ~ 2^63-1 0L
float 4字节 约±3.4E38 0.0f
double 8字节 约±1.7E308 0.0d
char 2字节 0 ~ 65535 ‘\u0000’
boolean 1位 true/false false

包装类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class DataTypeExample {

public void basicTypeExample() {
// 基本类型
int a = 10;
double b = 3.14;
boolean c = true;

// 包装类型
Integer a1 = 10; // 自动装箱
int a2 = a1; // 自动拆箱

// 字符串
String str = "Hello Java";

// 数组
int[] array = {1, 2, 3, 4, 5};
String[] strings = new String[10];
}
}

2.3 控制结构

2.3.1 条件语句和循环

控制结构示例

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class ControlStructure {

public void ifExample(int score) {
// if-else
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 80) {
System.out.println("良好");
} else if (score >= 60) {
System.out.println("及格");
} else {
System.out.println("不及格");
}

// switch
switch (score / 10) {
case 10:
case 9:
System.out.println("优秀");
break;
case 8:
System.out.println("良好");
break;
default:
System.out.println("其他");
}
}

public void loopExample() {
// for循环
for (int i = 0; i < 10; i++) {
System.out.println(i);
}

// 增强for循环
int[] array = {1, 2, 3, 4, 5};
for (int num : array) {
System.out.println(num);
}

// while循环
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}

// do-while循环
int j = 0;
do {
System.out.println(j);
j++;
} while (j < 10);
}
}

3. 面向对象编程

3.1 封装

3.1.1 封装的概念

封装:将数据和方法包装在类中,隐藏内部实现细节,只暴露必要的接口。

封装示例

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
33
34
35
public class BankAccount {

// 私有字段:隐藏内部数据
private String accountNumber;
private double balance;

// 构造方法
public BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}

// 公共方法:提供访问接口
public double getBalance() {
return balance;
}

public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("存款成功,余额:" + balance);
} else {
System.out.println("存款金额必须大于0");
}
}

public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("取款成功,余额:" + balance);
} else {
System.out.println("取款失败,余额不足或金额无效");
}
}
}

3.2 继承

3.2.1 继承的概念

继承:子类继承父类的属性和方法,实现代码复用。

继承示例

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
33
34
35
36
37
38
39
// 父类
public class Animal {
protected String name;
protected int age;

public Animal(String name, int age) {
this.name = name;
this.age = age;
}

public void eat() {
System.out.println(name + "正在吃东西");
}

public void sleep() {
System.out.println(name + "正在睡觉");
}
}

// 子类
public class Dog extends Animal {
private String breed;

public Dog(String name, int age, String breed) {
super(name, age); // 调用父类构造方法
this.breed = breed;
}

// 重写父类方法
@Override
public void eat() {
System.out.println(name + "(" + breed + ")正在吃狗粮");
}

// 子类特有方法
public void bark() {
System.out.println(name + "正在叫:汪汪汪");
}
}

3.3 多态

3.3.1 多态的概念

多态:同一接口,不同实现。包括编译时多态(方法重载)和运行时多态(方法重写)。

多态示例

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// 接口
public interface Shape {
double calculateArea();
double calculatePerimeter();
}

// 实现类1
public class Circle implements Shape {
private double radius;

public Circle(double radius) {
this.radius = radius;
}

@Override
public double calculateArea() {
return Math.PI * radius * radius;
}

@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}

// 实现类2
public class Rectangle implements Shape {
private double width;
private double height;

public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}

@Override
public double calculateArea() {
return width * height;
}

@Override
public double calculatePerimeter() {
return 2 * (width + height);
}
}

// 多态使用
public class PolymorphismExample {
public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);

// 多态:同一接口,不同实现
printShapeInfo(circle);
printShapeInfo(rectangle);
}

public static void printShapeInfo(Shape shape) {
System.out.println("面积:" + shape.calculateArea());
System.out.println("周长:" + shape.calculatePerimeter());
}
}

3.4 抽象类和接口

3.4.1 抽象类与接口的区别

抽象类:包含抽象方法的类,不能实例化。

接口:定义一组方法规范,Java 8支持默认方法和静态方法。

对比示例

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
33
34
35
36
37
38
39
40
41
42
43
44
45
// 抽象类
public abstract class AbstractAnimal {
protected String name;

// 抽象方法:子类必须实现
public abstract void makeSound();

// 普通方法:可以有实现
public void eat() {
System.out.println(name + "正在吃东西");
}
}

// 接口
public interface Flyable {
// 抽象方法
void fly();

// 默认方法(Java 8+)
default void takeOff() {
System.out.println("准备起飞");
}

// 静态方法(Java 8+)
static void showInfo() {
System.out.println("这是一个飞行接口");
}
}

// 实现类
public class Bird extends AbstractAnimal implements Flyable {
public Bird(String name) {
this.name = name;
}

@Override
public void makeSound() {
System.out.println(name + "在叫:啾啾啾");
}

@Override
public void fly() {
System.out.println(name + "正在飞行");
}
}

4. 集合框架

4.1 List集合

4.1.1 ArrayList和LinkedList

List接口:有序、可重复的集合。

ArrayList vs LinkedList

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.*;

public class ListExample {

public void arrayListExample() {
// ArrayList:基于数组,随机访问快,插入删除慢
List<String> arrayList = new ArrayList<>();
arrayList.add("Java");
arrayList.add("Python");
arrayList.add("C++");

// 遍历
for (String lang : arrayList) {
System.out.println(lang);
}

// 随机访问
String first = arrayList.get(0);

// 查找
int index = arrayList.indexOf("Python");
}

public void linkedListExample() {
// LinkedList:基于链表,插入删除快,随机访问慢
List<String> linkedList = new LinkedList<>();
linkedList.add("Java");
linkedList.add("Python");
linkedList.add("C++");

// 在头部插入(LinkedList优势)
linkedList.add(0, "Go");

// 在尾部插入
linkedList.add("Rust");
}

public void vectorExample() {
// Vector:线程安全的ArrayList(已过时,不推荐使用)
Vector<String> vector = new Vector<>();
vector.add("Java");

// 推荐使用Collections.synchronizedList替代
List<String> syncList = Collections.synchronizedList(new ArrayList<>());
}
}

4.2 Set集合

4.2.1 HashSet和TreeSet

Set接口:无序、不可重复的集合。

Set示例

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.*;

public class SetExample {

public void hashSetExample() {
// HashSet:基于HashMap,无序,O(1)查找
Set<String> hashSet = new HashSet<>();
hashSet.add("Java");
hashSet.add("Python");
hashSet.add("Java"); // 重复,不会添加

// 遍历(无序)
for (String lang : hashSet) {
System.out.println(lang);
}

// 查找
boolean contains = hashSet.contains("Java");
}

public void treeSetExample() {
// TreeSet:基于TreeMap,有序,O(log n)查找
Set<String> treeSet = new TreeSet<>();
treeSet.add("Java");
treeSet.add("Python");
treeSet.add("C++");

// 遍历(有序)
for (String lang : treeSet) {
System.out.println(lang); // 按字母顺序输出
}
}

public void linkedHashSetExample() {
// LinkedHashSet:保持插入顺序
Set<String> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add("Java");
linkedHashSet.add("Python");
linkedHashSet.add("C++");

// 遍历(保持插入顺序)
for (String lang : linkedHashSet) {
System.out.println(lang);
}
}
}

4.3 Map集合

4.3.1 HashMap和TreeMap

Map接口:键值对映射。

Map示例

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import java.util.*;

public class MapExample {

public void hashMapExample() {
// HashMap:基于哈希表,无序,O(1)查找
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("Java", 1);
hashMap.put("Python", 2);
hashMap.put("C++", 3);

// 获取值
Integer value = hashMap.get("Java");

// 遍历
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}

// 遍历key
for (String key : hashMap.keySet()) {
System.out.println(key);
}

// 遍历value
for (Integer val : hashMap.values()) {
System.out.println(val);
}
}

public void treeMapExample() {
// TreeMap:基于红黑树,有序,O(log n)查找
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("Java", 1);
treeMap.put("Python", 2);
treeMap.put("C++", 3);

// 遍历(有序)
for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
}

public void concurrentHashMapExample() {
// ConcurrentHashMap:线程安全的HashMap
Map<String, Integer> concurrentMap = new ConcurrentHashMap<>();
concurrentMap.put("Java", 1);
concurrentMap.put("Python", 2);

// 线程安全操作
concurrentMap.computeIfAbsent("C++", k -> 3);
}
}

5. 并发编程

5.1 多线程基础

5.1.1 线程创建

创建线程的方式

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class ThreadExample {

// 方式1:继承Thread类
static class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running: " + Thread.currentThread().getName());
}
}

// 方式2:实现Runnable接口
static class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Runnable running: " + Thread.currentThread().getName());
}
}

// 方式3:实现Callable接口(有返回值)
static class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return "Callable result: " + Thread.currentThread().getName();
}
}

public static void main(String[] args) throws Exception {
// 方式1
Thread thread1 = new MyThread();
thread1.start();

// 方式2
Thread thread2 = new Thread(new MyRunnable());
thread2.start();

// 方式3:使用Lambda表达式
Thread thread3 = new Thread(() -> {
System.out.println("Lambda thread running");
});
thread3.start();

// 方式4:使用Callable和Future
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new MyCallable());
String result = future.get();
System.out.println(result);
executor.shutdown();
}
}

5.2 线程同步

5.2.1 synchronized和Lock

线程同步:保证多线程访问共享资源的安全性。

同步示例

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
public class SynchronizationExample {

private int count = 0;
private final Object lock = new Object();
private final ReentrantLock reentrantLock = new ReentrantLock();

// 方式1:synchronized方法
public synchronized void increment1() {
count++;
}

// 方式2:synchronized代码块
public void increment2() {
synchronized (lock) {
count++;
}
}

// 方式3:ReentrantLock
public void increment3() {
reentrantLock.lock();
try {
count++;
} finally {
reentrantLock.unlock();
}
}

// 方式4:ReadWriteLock(读写锁)
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

public void read() {
readWriteLock.readLock().lock();
try {
// 读操作
System.out.println("Reading: " + count);
} finally {
readWriteLock.readLock().unlock();
}
}

public void write() {
readWriteLock.writeLock().lock();
try {
// 写操作
count++;
} finally {
readWriteLock.writeLock().unlock();
}
}
}

5.3 线程池

5.3.1 线程池的使用

线程池:复用线程,提高性能。

线程池示例

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.concurrent.*;

public class ThreadPoolExample {

public void executorServiceExample() {
// 创建线程池
ExecutorService executor = Executors.newFixedThreadPool(10);

// 提交任务
for (int i = 0; i < 100; i++) {
final int taskId = i;
executor.submit(() -> {
System.out.println("Task " + taskId + " running in " +
Thread.currentThread().getName());
});
}

// 关闭线程池
executor.shutdown();
try {
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
executor.shutdownNow();
}
} catch (InterruptedException e) {
executor.shutdownNow();
}
}

public void customThreadPoolExample() {
// 自定义线程池
ThreadPoolExecutor executor = new ThreadPoolExecutor(
5, // 核心线程数
10, // 最大线程数
60L, // 空闲线程存活时间
TimeUnit.SECONDS, // 时间单位
new LinkedBlockingQueue<>(100), // 工作队列
new ThreadFactory() { // 线程工厂
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName("CustomThread-" + thread.getId());
return thread;
}
},
new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
);

// 提交任务
executor.submit(() -> System.out.println("Custom thread pool task"));

// 关闭
executor.shutdown();
}
}

5.4 并发工具类

5.4.1 CountDownLatch、CyclicBarrier、Semaphore

并发工具类:简化并发编程。

工具类示例

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.concurrent.*;

public class ConcurrentToolsExample {

// CountDownLatch:等待多个线程完成
public void countDownLatchExample() throws InterruptedException {
CountDownLatch latch = new CountDownLatch(3);

for (int i = 0; i < 3; i++) {
new Thread(() -> {
System.out.println("Task completed");
latch.countDown();
}).start();
}

latch.await(); // 等待所有任务完成
System.out.println("All tasks completed");
}

// CyclicBarrier:多个线程互相等待
public void cyclicBarrierExample() {
CyclicBarrier barrier = new CyclicBarrier(3, () -> {
System.out.println("All threads reached barrier");
});

for (int i = 0; i < 3; i++) {
new Thread(() -> {
try {
System.out.println("Thread waiting at barrier");
barrier.await();
System.out.println("Thread passed barrier");
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}

// Semaphore:控制并发数量
public void semaphoreExample() {
Semaphore semaphore = new Semaphore(3); // 允许3个线程同时执行

for (int i = 0; i < 10; i++) {
new Thread(() -> {
try {
semaphore.acquire(); // 获取许可
System.out.println("Thread running: " + Thread.currentThread().getName());
Thread.sleep(1000);
semaphore.release(); // 释放许可
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}

// CompletableFuture:异步编程
public void completableFutureExample() {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
return "Hello";
}).thenApply(s -> s + " World")
.thenApply(String::toUpperCase);

future.thenAccept(result -> {
System.out.println("Result: " + result);
});
}
}

6. JVM原理

6.1 内存模型

6.1.1 JVM内存结构

JVM内存结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class JVMMemoryModel {

// 方法区(元空间):存储类信息、常量、静态变量
private static String staticField = "Static Field";

// 堆:存储对象实例
public void heapExample() {
Object obj = new Object(); // 对象在堆中分配
}

// 栈:存储局部变量、方法参数
public void stackExample(int param) {
int localVar = 10; // 局部变量在栈中
}

// 程序计数器:记录当前执行指令地址
// 本地方法栈:Native方法使用
}

内存参数调优

1
2
3
4
5
6
7
8
9
# JVM参数示例
java -Xms2g # 初始堆大小
-Xmx4g # 最大堆大小
-Xmn1g # 新生代大小
-XX:MetaspaceSize=256m # 元空间初始大小
-XX:MaxMetaspaceSize=512m # 元空间最大大小
-XX:+UseG1GC # 使用G1垃圾回收器
-XX:MaxGCPauseMillis=200 # 最大GC暂停时间
YourApplication

6.2 垃圾回收

6.2.1 GC算法和收集器

垃圾回收算法

  1. 标记-清除:标记垃圾对象,清除
  2. 标记-复制:复制存活对象到新区域
  3. 标记-整理:标记后整理,消除碎片

垃圾回收器

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
public class GarbageCollectionExample {

public void gcExample() {
// 创建大量对象
for (int i = 0; i < 1000000; i++) {
Object obj = new Object();
// obj超出作用域后,成为垃圾对象
}

// 手动触发GC(不推荐,仅用于测试)
System.gc();
}

// 对象生命周期
public void objectLifecycle() {
// 1. 对象创建
MyObject obj = new MyObject();

// 2. 对象使用
obj.doSomething();

// 3. 对象引用置为null
obj = null;

// 4. 对象成为垃圾,等待GC回收
}
}

GC调优

1
2
3
4
5
6
7
8
9
10
11
# 查看GC日志
java -XX:+PrintGCDetails
-XX:+PrintGCDateStamps
-Xloggc:gc.log
YourApplication

# G1垃圾回收器参数
java -XX:+UseG1GC
-XX:MaxGCPauseMillis=200
-XX:G1HeapRegionSize=16m
YourApplication

6.3 性能调优

6.3.1 JVM性能调优

性能调优技巧

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
33
34
35
36
37
38
39
40
public class PerformanceOptimization {

// 1. 避免创建不必要的对象
public void avoidUnnecessaryObjects() {
// 不好:每次都创建新对象
String str1 = new String("Hello");

// 好:使用字符串常量池
String str2 = "Hello";
}

// 2. 使用StringBuilder代替String拼接
public void stringBuilderExample() {
// 不好:创建多个String对象
String result = "";
for (int i = 0; i < 1000; i++) {
result += i;
}

// 好:使用StringBuilder
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++) {
sb.append(i);
}
String result2 = sb.toString();
}

// 3. 合理使用集合
public void collectionOptimization() {
// 指定初始容量,避免扩容
List<String> list = new ArrayList<>(1000);
Map<String, String> map = new HashMap<>(1000);
}

// 4. 使用对象池
public void objectPoolExample() {
// 复用对象,减少GC压力
// 使用Apache Commons Pool等工具
}
}

7. 设计模式

7.1 单例模式

7.1.1 单例模式实现

单例模式:确保一个类只有一个实例。

实现方式

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// 方式1:饿汉式
public class Singleton1 {
private static final Singleton1 INSTANCE = new Singleton1();

private Singleton1() {}

public static Singleton1 getInstance() {
return INSTANCE;
}
}

// 方式2:懒汉式(线程安全)
public class Singleton2 {
private static volatile Singleton2 INSTANCE;

private Singleton2() {}

public static Singleton2 getInstance() {
if (INSTANCE == null) {
synchronized (Singleton2.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton2();
}
}
}
return INSTANCE;
}
}

// 方式3:静态内部类(推荐)
public class Singleton3 {
private Singleton3() {}

private static class Holder {
private static final Singleton3 INSTANCE = new Singleton3();
}

public static Singleton3 getInstance() {
return Holder.INSTANCE;
}
}

// 方式4:枚举(推荐,线程安全,防止反射和序列化)
public enum Singleton4 {
INSTANCE;

public void doSomething() {
System.out.println("Singleton method");
}
}

7.2 工厂模式

7.2.1 工厂模式实现

工厂模式:创建对象而不暴露创建逻辑。

工厂模式示例

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// 产品接口
public interface Product {
void use();
}

// 具体产品
public class ProductA implements Product {
@Override
public void use() {
System.out.println("Using Product A");
}
}

public class ProductB implements Product {
@Override
public void use() {
System.out.println("Using Product B");
}
}

// 工厂接口
public interface ProductFactory {
Product createProduct();
}

// 具体工厂
public class ProductAFactory implements ProductFactory {
@Override
public Product createProduct() {
return new ProductA();
}
}

public class ProductBFactory implements ProductFactory {
@Override
public Product createProduct() {
return new ProductB();
}
}

// 使用
public class FactoryExample {
public static void main(String[] args) {
ProductFactory factory = new ProductAFactory();
Product product = factory.createProduct();
product.use();
}
}

7.3 观察者模式

7.3.1 观察者模式实现

观察者模式:定义对象间一对多的依赖关系。

观察者模式示例

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.*;

// 观察者接口
public interface Observer {
void update(String message);
}

// 被观察者
public class Subject {
private List<Observer> observers = new ArrayList<>();

public void addObserver(Observer observer) {
observers.add(observer);
}

public void removeObserver(Observer observer) {
observers.remove(observer);
}

public void notifyObservers(String message) {
for (Observer observer : observers) {
observer.update(message);
}
}
}

// 具体观察者
public class ConcreteObserver implements Observer {
private String name;

public ConcreteObserver(String name) {
this.name = name;
}

@Override
public void update(String message) {
System.out.println(name + " received: " + message);
}
}

// 使用
public class ObserverExample {
public static void main(String[] args) {
Subject subject = new Subject();
subject.addObserver(new ConcreteObserver("Observer 1"));
subject.addObserver(new ConcreteObserver("Observer 2"));

subject.notifyObservers("Hello Observers!");
}
}

8. 框架应用

8.1 Spring框架

8.1.1 Spring核心概念

Spring框架:IoC容器和AOP框架。

Spring示例

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// 服务接口
public interface UserService {
void saveUser(User user);
User getUserById(Long id);
}

// 服务实现
@Service
public class UserServiceImpl implements UserService {

@Autowired
private UserRepository userRepository;

@Override
@Transactional
public void saveUser(User user) {
userRepository.save(user);
}

@Override
public User getUserById(Long id) {
return userRepository.findById(id);
}
}

// Repository
@Repository
public class UserRepository {
public void save(User user) {
// 保存用户
}

public User findById(Long id) {
// 查找用户
return null;
}
}

// Controller
@RestController
@RequestMapping("/users")
public class UserController {

@Autowired
private UserService userService;

@PostMapping
public ResponseEntity<String> createUser(@RequestBody User user) {
userService.saveUser(user);
return ResponseEntity.ok("User created");
}

@GetMapping("/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
User user = userService.getUserById(id);
return ResponseEntity.ok(user);
}
}

8.2 MyBatis框架

8.2.1 MyBatis使用

MyBatis:持久层框架。

MyBatis示例

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
// Mapper接口
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{id}")
User findById(Long id);

@Insert("INSERT INTO users(name, email) VALUES(#{name}, #{email})")
@Options(useGeneratedKeys = true, keyProperty = "id")
void insert(User user);

@Update("UPDATE users SET name = #{name} WHERE id = #{id}")
void update(User user);

@Delete("DELETE FROM users WHERE id = #{id}")
void delete(Long id);
}

// XML映射文件(UserMapper.xml)
// <?xml version="1.0" encoding="UTF-8"?>
// <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
// "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
// <mapper namespace="com.example.mapper.UserMapper">
// <select id="findById" resultType="User">
// SELECT * FROM users WHERE id = #{id}
// </select>
// </mapper>

9. 性能优化

9.1 代码优化

9.1.1 性能优化技巧

代码优化示例

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class CodeOptimization {

// 1. 使用局部变量
public void useLocalVariable() {
// 局部变量访问比成员变量快
int localVar = 10;
}

// 2. 减少方法调用
public void reduceMethodCalls() {
// 不好:多次调用length()
String str = "Hello";
for (int i = 0; i < str.length(); i++) {
// ...
}

// 好:缓存length
int len = str.length();
for (int i = 0; i < len; i++) {
// ...
}
}

// 3. 使用基本类型
public void usePrimitiveType() {
// 不好:使用包装类型
Integer sum = 0;
for (int i = 0; i < 1000; i++) {
sum += i; // 自动装箱/拆箱
}

// 好:使用基本类型
int sum2 = 0;
for (int i = 0; i < 1000; i++) {
sum2 += i;
}
}

// 4. 合理使用缓存
public void useCache() {
// 缓存计算结果
Map<String, Integer> cache = new HashMap<>();

public int calculate(String key) {
if (cache.containsKey(key)) {
return cache.get(key);
}
int result = expensiveCalculation(key);
cache.put(key, result);
return result;
}
}
}

10. 总结

10.1 核心要点

  1. 基础扎实:掌握Java基础语法和面向对象编程
  2. 集合熟练:熟练使用各种集合框架
  3. 并发掌握:理解多线程和并发编程
  4. JVM理解:理解JVM原理和性能调优
  5. 设计模式:掌握常用设计模式
  6. 框架应用:熟练使用主流框架
  7. 性能优化:掌握性能优化技巧

10.2 学习路径

  1. 基础阶段:Java语法、面向对象、集合框架
  2. 进阶阶段:并发编程、JVM原理、设计模式
  3. 应用阶段:框架使用、项目实战
  4. 精通阶段:性能优化、架构设计

10.3 实践建议

  1. 多写代码:通过实践加深理解
  2. 阅读源码:阅读JDK和框架源码
  3. 性能测试:进行性能测试和调优
  4. 项目实战:通过项目积累经验

相关文章