第八章 多线程
基本概念
程序 vs 进程 vs 线程
概念 | 特点 | 比喻 |
---|
程序 | 静态代码文件 | 菜谱(纸上步骤) |
进程 | 动态执行的程序 | 正在炒菜的过程(占用厨房资源) |
线程 | 进程内的执行路径 | 厨师同时做多道菜(共享厨房资源) |
多线程核心特性
线程创建方式
两种经典方法对比
方式 | 实现步骤 | 特点 |
---|
继承Thread类 | 1. 继承Thread 2. 重写run() 3. start()启动 | 简单但受限于单继承 |
实现Runnable接口 | 1. 实现Runnable 2. 重写run() 3. 通过Thread启动 | 灵活可共享资源,推荐使用 |
```java
// 实现Runnable示例
class MyRunnable implements Runnable {
public void run() {
System.out.println("线程运行中");
}
}
new Thread(new MyRunnable()).start();
线程生命周期
🔒 线程同步机制
synchronized vs Lock
特性 | synchronized | Lock |
---|
锁类型 | 隐式锁(自动释放) | 显式锁(手动unlock) |
锁范围 | 代码块/方法 | 只能代码块 |
性能 | 较低 | 更高 |
中断响应 | 不支持 | 支持 |
同步代码示例
public synchronized void safeMethod() {
}
Lock lock = new ReentrantLock();
public void safeMethod() {
lock.lock();
try {
} finally {
lock.unlock();
}
}
📡 线程通信
生产者-消费者模型要点
- 共享资源类(如仓库)需要同步方法
- wait():让当前线程等待并释放锁
- notifyAll():唤醒所有等待线程
🆕 JDK5+新特性
线程池使用三步曲
ExecutorService pool = Executors.newFixedThreadPool(5);
pool.execute(new RunnableTask());
pool.shutdown();
Callable与Runnable对比
特性 | Runnable | Callable |
---|
返回值 | void | 泛型类型 |
异常抛出 | 不可抛出 | 可抛出 |
适用场景 | 简单异步任务 | 需要返回结果的任务 |
第九章 Java常用类
字符串处理三剑客
String类特性
创建方式 | 存储位置 | 示例 |
---|
String s = “abc” | 常量池 | 复用相同值对象 |
new String(“abc”) | 堆内存 | 每次新建独立对象 |
String vs StringBuffer vs StringBuilder
特性 | String | StringBuffer | StringBuilder |
---|
可变性 | ❌ 不可变 | ✅ 可变 | ✅ 可变 |
线程安全 | - | ✅ 同步方法 | ❌ 非同步 |
性能 | 低(频繁修改) | 中等 | 高 |
适用场景 | 少量字符串操作 | 多线程环境字符串操作 | 单线程环境字符串操作 |
StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" World!");
System.out.println(sb.toString());
📅 日期时间处理
JDK8新旧API对比
timeline
title 日期时间API进化史
section JDK8前
Date : 1970时间戳, 线程不安全
SimpleDateFormat : 格式化易出错, 线程不安全
section JDK8+
LocalDate : 日期, 不可变, 线程安全
LocalTime : 时间, 不可变, 线程安全
LocalDateTime : 日期时间, 不可变, 线程安全
新API基础操作
LocalDate today = LocalDate.now();
LocalTime now = LocalTime.now();
LocalDateTime current = LocalDateTime.now();
LocalDate nextWeek = today.plusWeeks(1);
LocalDateTime inTwoHours = current.plusHours(2);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
String formatted = current.format(formatter);
⚖️ 对象比较器
Comparable vs Comparator
比较方式 | 实现方式 | 使用场景 |
---|
自然排序 | 实现Comparable接口 | 类本身支持默认排序规则 |
定制排序 | 创建Comparator实现类 | 临时定义特殊排序规则 |
class Product implements Comparable<Product> {
public int compareTo(Product other) {
return Double.compare(this.price, other.price);
}
}
Comparator<Product> nameLengthComparator = new Comparator<>() {
public int compare(Product p1, Product p2) {
return p1.getName().length() - p2.getName().length();
}
};
🔢 大数处理
BigInteger与BigDecimal
类 | 解决的问题 | 核心方法 |
---|
BigInteger | 超长整数运算 | add/subtract/multiply/divide |
BigDecimal | 高精度浮点数运算 | setScale(保留小数位数) |
BigInteger bigInt = new BigInteger("12345678901234567890");
BigDecimal decimal = new BigDecimal("3.14159265358979323846");
BigDecimal result = decimal.divide(new BigDecimal("2"), 10, RoundingMode.HALF_UP);
🛠️ 常用工具类
System类核心方法
String osName = System.getProperty("os.name");
String userDir = System.getProperty("user.dir");
long start = System.currentTimeMillis();
long duration = System.currentTimeMillis() - start;
Math类常用功能
double sqrt = Math.sqrt(25);
double pow = Math.pow(2, 10);
double random = Math.random();
long round = Math.round(3.14159);
double ceil = Math.ceil(3.1);
double floor = Math.floor(3.9);
第十章 枚举类与注解
枚举类(Enum)
枚举类的本质
自定义枚举类 vs enum关键字
特性 | 自定义枚举类 | enum关键字实现 |
---|
继承关系 | 默认继承Object类 | 隐式继承java.lang.Enum类 |
构造器权限 | 可自定义(通常private) | 必须private |
实例声明 | 需要显式声明public static final | 自动添加public static final修饰 |
switch支持 | ❌ 不支持 | ✅ 直接使用枚举常量名 |
方法实现 | 可在类内统一实现 | 支持每个枚举常量单独实现方法 |
Enum类核心方法
SeasonEnum spring = SeasonEnum.SPRING;
System.out.println(spring.name());
System.out.println(spring.ordinal());
SeasonEnum[] values = SeasonEnum.values();
SeasonEnum autumn = SeasonEnum.valueOf("AUTUMN");
注解(Annotation)
注解分类图解
mindmap
root((注解类型))
标记注解
无成员变量
@Override
元数据注解
包含成员变量
@SuppressWarnings("unchecked")
元注解
修饰注解的注解
@Retention
@Target
四大元注解详解
元注解 | 作用描述 | 常用取值 |
---|
@Retention | 定义注解生命周期 | SOURCE/CLASS/RUNTIME |
@Target | 定义注解作用目标 | TYPE/METHOD/FIELD/PARAMETER等 |
@Documented | 是否包含在Javadoc中 | —— |
@Inherited | 是否允许子类继承父类注解 | —— |
自定义注解模板
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
String value() default "default";
boolean enable() default true;
}
JDK8注解新特性
List<@NonNull String> list = new ArrayList<>();
@Role("admin")
@Role("user")
public class User {
@Retention(RetentionPolicy.RUNTIME)
public @interface Roles {
Role[] value();
}
}
关键实践技巧
-
枚举使用场景
public enum Singleton {
INSTANCE;
public void doSomething() { ... }
}
-
注解开发技巧
Method method = obj.getClass().getMethod("test");
if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation anno = method.getAnnotation(MyAnnotation.class);
System.out.println(anno.value());
}
-
调试技巧
Arrays.stream(MyClass.class.getAnnotations())
.forEach(System.out::println);
