尚硅谷2019版多线程以及枚举类笔记记录

第八章 多线程

基本概念

程序 vs 进程 vs 线程

概念特点比喻
程序静态代码文件菜谱(纸上步骤)
进程动态执行的程序正在炒菜的过程(占用厨房资源)
线程进程内的执行路径厨师同时做多道菜(共享厨房资源)

多线程核心特性

多线程优势
提高响应速度
提高CPU利用率
改善程序结构

线程创建方式

两种经典方法对比

方式实现步骤特点
继承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();

线程生命周期

new Thread()
start()
获取CPU
sleep()/wait()
yield()/时间片用完
条件满足
run()结束/异常
新建
就绪
运行
阻塞
死亡

🔒 线程同步机制

synchronized vs Lock

特性synchronizedLock
锁类型隐式锁(自动释放)显式锁(手动unlock)
锁范围代码块/方法只能代码块
性能较低更高
中断响应不支持支持

同步代码示例

// 使用synchronized
public synchronized void safeMethod() {
    // 操作共享资源
}

// 使用ReentrantLock
Lock lock = new ReentrantLock();
public void safeMethod() {
    lock.lock();
    try {
        // 操作共享资源
    } finally {
        lock.unlock();
    }
}

📡 线程通信

生产者-消费者模型要点

  1. 共享资源类(如仓库)需要同步方法
  2. wait():让当前线程等待并释放锁
  3. notifyAll():唤醒所有等待线程
生产者 仓库 消费者 生产产品(仓库满则wait) 通知可取货 消费产品(仓库空则wait) 通知可生产 生产者 仓库 消费者

🆕 JDK5+新特性

线程池使用三步曲

ExecutorService pool = Executors.newFixedThreadPool(5); // 1.创建线程池
pool.execute(new RunnableTask());                       // 2.提交任务
pool.shutdown();                                        // 3.关闭线程池

Callable与Runnable对比

特性RunnableCallable
返回值void泛型类型
异常抛出不可抛出可抛出
适用场景简单异步任务需要返回结果的任务

第九章 Java常用类

字符串处理三剑客

String类特性

String
不可变性
修改会创建新对象
存储在字符串常量池
复用相同字符串
创建方式存储位置示例
String s = “abc”常量池复用相同值对象
new String(“abc”)堆内存每次新建独立对象

String vs StringBuffer vs StringBuilder

特性StringStringBufferStringBuilder
可变性❌ 不可变✅ 可变✅ 可变
线程安全-✅ 同步方法❌ 非同步
性能低(频繁修改)中等
适用场景少量字符串操作多线程环境字符串操作单线程环境字符串操作
// StringBuilder快速拼接示例
StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" World!");
System.out.println(sb.toString()); // Hello World!

📅 日期时间处理

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);      // 5.0
double pow = Math.pow(2, 10);     // 1024.0
double random = Math.random();    // [0,1)随机数

// 取整运算
long round = Math.round(3.14159); // 3
double ceil = Math.ceil(3.1);     // 4.0
double floor = Math.floor(3.9);   // 3.0

选择工具类
需要可变字符串?
线程安全要求?
StringBuffer
StringBuilder
String

第十章 枚举类与注解

枚举类(Enum)

枚举类的本质

«abstract»
Enum
+name() : String
+ordinal() : int
+values() : Enum[]
+valueOf() : Enum
SeasonEnum
-seasonName: String
-seasonDesc: String
+SPRING
+SUMMER
+AUTUMN
+WINTER
+getSeasonName()
+getSeasonDesc()

自定义枚举类 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());      // SPRING
// 获取声明顺序
System.out.println(spring.ordinal());   // 0
// 获取所有枚举值
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";  // 参数类型支持:
                                        // 基本类型/String/Class/枚举/注解/数组
    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();
    }
}

关键实践技巧

  1. 枚举使用场景

    • 状态机实现(如订单状态流转)
    • 单例模式实现
    public enum Singleton {
        INSTANCE;
        public void doSomething() { ... }
    }
    
  2. 注解开发技巧

    • 结合反射实现动态处理
    Method method = obj.getClass().getMethod("test");
    if (method.isAnnotationPresent(MyAnnotation.class)) {
        MyAnnotation anno = method.getAnnotation(MyAnnotation.class);
        System.out.println(anno.value());
    }
    
  3. 调试技巧

    // 查看运行时注解信息
    Arrays.stream(MyClass.class.getAnnotations())
          .forEach(System.out::println);
    

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值