《Java进阶指南!看完直接起飞!》

Java核心基础速成:从入门到实战的八大模块详解

还在为Java基础知识杂乱无章而发愁?
还在为不知从何学起而焦虑?
别急,这篇文章就是你的"Java百宝箱"!
我们把Java最核心的八大模块,像拆解乐高积木一样,一块块清晰地展现在你面前。
无论你是想快速查漏补缺的老司机,还是刚踏上编程之路的新手,这篇文章都能让你找到自己的"专属路线"。
每个知识点都配备了实战案例,就像给你配了一把"通关钥匙",学起来不费力!

文章大纲:
🌟 第一章:Java基础语法 - 编程世界的"入场券"
🏗️ 第二章:面向对象编程 - 代码世界的"积木游戏"
🎯 第三章:异常处理 - 程序的"安全气囊"
🧠 第四章:内存管理 - JVM的"内部故事"
📚 第五章:常用类库 - 开发者的"百宝箱"
📂 第六章:输入输出 - 数据的"高速公路"
🔄 第七章:多线程编程 - 并发的"交通指挥"
🎨 第八章:设计模式 - 架构的"艺术殿堂"

⚠️ 友情提示:本文约30分钟阅读时间,建议先点赞收藏,再慢慢享用!

🚗 发车准备:

  1. 准备一杯咖啡☕️
  2. 找个舒适的姿势🪑
  3. 打开你的IDE(想动手练习的话)💻
  4. 系好安全带,开始我们的Java学习之旅!🚀

第一章 Java基础语法

1. 语法结构

1.1 类的定义

Java程序的基本单位是类(class)。每个类都需要有一个与文件名相同的公共类名。

public class HelloWorld {
    // 类的内容
}
1.2 主方法

Java程序的入口点是main方法,格式如下:

public static void main(String[] args) {
    // 程序代码
}
1.3 变量声明与使用
// 变量声明与初始化
int age = 25;                 // 整数
double salary = 5000.50;      // 浮点数
String name = "张三";         // 字符串
boolean isStudent = true;     // 布尔值

// 常量声明(使用final关键字)
final double PI = 3.14159;
1.4 控制流语句
// if-else条件语句
if (age >= 18) {
    System.out.println("成年人");
} else {
    System.out.println("未成年人");
}

// for循环
for (int i = 0; i < 5; i++) {
    System.out.println("第" + i + "次循环");
}

// while循环
int count = 0;
while (count < 3) {
    System.out.println("count: " + count);
    count++;
}

2. 数据类型

2.1 基本数据类型

Java有8种基本数据类型:

  1. 整数类型:

    • byte(1字节):-128 ~ 127
    • short(2字节):-32768 ~ 32767
    • int(4字节):-2^31 ~ 2^31-1
    • long(8字节):-2^63 ~ 2^63-1
  2. 浮点类型:

    • float(4字节):单精度浮点数
    • double(8字节):双精度浮点数
  3. 字符类型:

    • char(2字节):存储单个字符
  4. 布尔类型:

    • boolean:true或false
2.2 引用数据类型

引用数据类型包括:

  • 类(Class)
  • 接口(Interface)
  • 数组(Array)
  • 字符串(String)
2.3 代码示例
public class DataTypeDemo {
    public static void main(String[] args) {
        // 基本类型示例
        byte b = 100;
        short s = 1000;
        int i = 100000;
        long l = 1000000000L;
        float f = 3.14f;
        double d = 3.14159;
        char c = 'A';
        boolean bool = true;

        // 引用类型示例
        String str = "Hello Java";
        int[] arr = {1, 2, 3, 4, 5};
        
        // 输出验证
        System.out.println("整数类型:" + i);
        System.out.println("浮点类型:" + d);
        System.out.println("字符类型:" + c);
        System.out.println("字符串类型:" + str);
    }
}

3. 运算符

3.1 算术运算符
int a = 10, b = 3;
System.out.println("加法:" + (a + b));    // 13
System.out.println("减法:" + (a - b));    // 7
System.out.println("乘法:" + (a * b));    // 30
System.out.println("除法:" + (a / b));    // 3
System.out.println("取余:" + (a % b));    // 1
3.2 关系运算符
int x = 5, y = 8;
System.out.println("x > y: " + (x > y));   // false
System.out.println("x < y: " + (x < y));   // true
System.out.println("x == y: " + (x == y)); // false
3.3 逻辑运算符
boolean a = true, b = false;
System.out.println("逻辑与:" + (a && b)); // false
System.out.println("逻辑或:" + (a || b)); // true
System.out.println("逻辑非:" + (!a));     // false

第二章 面向对象编程

1. 类与对象基础

1.1 类的定义与对象创建
public class Student {
    // 属性(成员变量)
    private String name;
    private int age;
    private String studentId;
    
    // 构造方法
    public Student(String name, int age, String studentId) {
        this.name = name;
        this.age = age;
        this.studentId = studentId;
    }
    
    // 方法
    public void study() {
        System.out.println(name + "正在学习");
    }
    
    // getter和setter方法
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
}
1.2 对象的创建与使用
public class Main {
    public static void main(String[] args) {
        // 创建对象
        Student student1 = new Student("张三", 20, "2024001");
        Student student2 = new Student("李四", 19, "2024002");
        
        // 调用对象的方法
        student1.study();
        System.out.println("学生姓名:" + student2.getName());
    }
}

2. 三大特性

2.1 封装(Encapsulation)

封装是将数据和操作数据的方法绑定在一起,对外部隐藏实现细节。

public class BankAccount {
    private double balance;  // 私有属性
    
    // 公共方法操作私有属性
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("存款成功,当前余额:" + balance);
        }
    }
    
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("取款成功,当前余额:" + balance);
        } else {
            System.out.println("余额不足或金额无效");
        }
    }
}
2.2 继承(Inheritance)

继承允许创建一个类作为另一个类的扩展,复用代码并建立类之间的关系。

// 父类
public class Animal {
    protected String name;
    
    public Animal(String name) {
        this.name = name;
    }
    
    public void eat() {
        System.out.println(name + "正在吃东西");
    }
}

// 子类
public class Dog extends Animal {
    private String breed;
    
    public Dog(String name, String breed) {
        super(name);  // 调用父类构造方法
        this.breed = breed;
    }
    
    public void bark() {
        System.out.println(name + "汪汪叫");
    }
    
    // 方法重写
    @Override
    public void eat() {
        System.out.println(name + "在啃骨头");
    }
}
2.3 多态(Polymorphism)

多态允许使用父类类型引用子类对象,实现接口的统一性和灵活性。

public class PolymorphismDemo {
    public static void main(String[] args) {
        // 多态的体现
        Animal animal1 = new Dog("旺财", "柴犬");
        Animal animal2 = new Cat("咪咪");
        
        // 调用相同的方法会有不同的行为
        animal1.eat();  // 输出:旺财在啃骨头
        animal2.eat();  // 输出:咪咪在吃鱼
        
        // 类型转换
        if (animal1 instanceof Dog) {
            Dog dog = (Dog) animal1;
            dog.bark();  // 调用Dog特有的方法
        }
    }
}

3. 抽象类与接口

3.1 抽象类(Abstract Class)

抽象类提供了一个不完整的实现,需要子类来完成。

public abstract class Shape {
    protected String color;
    
    public Shape(String color) {
        this.color = color;
    }
    
    // 抽象方法
    public abstract double getArea();
    
    // 具体方法
    public void displayColor() {
        System.out.println("颜色是:" + color);
    }
}

// 实现抽象类
public class Circle extends Shape {
    private double radius;
    
    public Circle(String color, double radius) {
        super(color);
        this.radius = radius;
    }
    
    @Override
    public double getArea() {
        return Math.PI * radius * radius;
    }
}
3.2 接口(Interface)

接口定义了一组抽象方法,实现类必须提供这些方法的具体实现。

public interface Flyable {
    void fly();
    void land();
}

public interface Swimmable {
    void swim();
}

// 实现多个接口
public class Duck implements Flyable, Swimmable {
    private String name;
    
    public Duck(String name) {
        this.name = name;
    }
    
    @Override
    public void fly() {
        System.out.println(name + "正在飞");
    }
    
    @Override
    public void land() {
        System.out.println(name + "降落了");
    }
    
    @Override
    public void swim() {
        System.out.println(name + "在游泳");
    }
}

第三章 异常处理

1. 异常体系

1.1 异常层次结构
// Java异常层次结构示意
Throwable
 ├── Error(错误)
 │    ├── OutOfMemoryError
 │    ├── StackOverflowError
 │    └── ...
 └── Exception(异常)
      ├── RuntimeException(非检查型异常)
      │    ├── NullPointerException
      │    ├── ArrayIndexOutOfBoundsException
      │    ├── ClassCastException
      │    └── ...
      └── IOException等(检查型异常)
           ├── FileNotFoundException
           ├── SQLException
           └── ...
1.2 检查型异常与非检查型异常
  1. 检查型异常(Checked Exception):

    • 必须显式处理或声明抛出
    • 在编译时检查
    • 例如:IOException, SQLException
  2. 非检查型异常(Unchecked Exception):

    • 不强制处理
    • 运行时异常
    • 例如:NullPointerException, ArrayIndexOutOfBoundsException

2. 异常处理结构

2.1 try-catch基本结构
public class ExceptionDemo {
    public static void main(String[] args) {
        try {
            // 可能抛出异常的代码
            int result = divide(10, 0);
            System.out.println("结果:" + result);
        } catch (ArithmeticException e) {
            // 处理特定类型的异常
            System.out.println("发生算术异常:" + e.getMessage());
        } catch (Exception e) {
            // 处理其他类型的异常
            System.out.println("发生其他异常:" + e.getMessage());
        }
    }
    
    public static int divide(int a, int b) {
        return a / b;
    }
}
2.2 try-catch-finally结构
public class FileProcessDemo {
    public static void readFile(String filename) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(filename));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            System.out.println("文件不存在:" + e.getMessage());
        } catch (IOException e) {
            System.out.println("读取文件出错:" + e.getMessage());
        } finally {
            // 无论是否发生异常,都会执行
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                System.out.println("关闭文件出错:" + e.getMessage());
            }
        }
    }
}
2.3 try-with-resources结构(Java 7+)
public class ModernFileProcessDemo {
    public static void readFile(String filename) {
        // 自动关闭资源
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            System.out.println("文件处理错误:" + e.getMessage());
        }
    }
}

3. 自定义异常

3.1 创建自定义异常类
// 自定义检查型异常
public class InvalidAgeException extends Exception {
    public InvalidAgeException() {
        super();
    }
    
    public InvalidAgeException(String message) {
        super(message);
    }
    
    public InvalidAgeException(String message, Throwable cause) {
        super(message, cause);
    }
}

// 自定义运行时异常
public class BusinessException extends RuntimeException {
    private String errorCode;
    
    public BusinessException(String errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }
    
    public String getErrorCode() {
        return errorCode;
    }
}
3.2 使用自定义异常
public class PersonService {
    public void validateAge(int age) throws InvalidAgeException {
        if (age < 0) {
            throw new InvalidAgeException("年龄不能为负数");
        }
        if (age > 150) {
            throw new InvalidAgeException("年龄超出正常范围");
        }
    }
    
    public void processBusiness(String data) {
        if (data == null || data.isEmpty()) {
            throw new BusinessException("ERR001", "数据不能为空");
        }
        // 处理业务逻辑
    }
}

第四章 Java内存管理

1. JVM内存结构

1.1 内存区域划分
JVM内存结构
├── 堆(Heap)
│   ├── 新生代(Young Generation)
│   │   ├── Eden区
│   │   ├── Survivor 0区
│   │   └── Survivor 1区
│   └── 老年代(Old Generation)
├── 栈(Stack)
│   ├── 局部变量表
│   ├── 操作数栈
│   └── 动态链接
├── 方法区(Method Area)
│   ├── 类信息
│   ├── 常量
│   └── 静态变量
└── 其他(本地方法栈、程序计数器)
1.2 栈内存示例
public class StackMemoryDemo {
    public static void main(String[] args) {
        int x = 10;          // 基本类型,直接存储在栈中
        int y = 20;
        String name = "Java"; // 引用存储在栈中,实际字符串在堆中
        
        calculateSum(x, y);   // 方法调用会创建新的栈帧
    }
    
    public static void calculateSum(int a, int b) {
        int result = a + b;   // 局部变量存储在栈中
        System.out.println("Sum: " + result);
    } // 方法结束时,栈帧被销毁
}
1.3 堆内存示例
public class HeapMemoryDemo {
    public static void main(String[] args) {
        // 在堆中创建对象
        Person person1 = new Person("张三", 25);
        Person person2 = new Person("李四", 30);
        
        // 数组也存储在堆中
        int[] numbers = new int[1000];
        
        // String对象的特殊性
        String str1 = "Hello";           // 字符串常量池
        String str2 = new String("Hello"); // 堆内存
    }
}

2. 垃圾回收机制

2.1 垃圾回收算法
public class GCDemo {
    public static void main(String[] args) {
        // 创建大量对象
        for (int i = 0; i < 1000000; i++) {
            Object obj = new Object();
            // obj变量离开作用域后,对象成为垃圾
        }
        
        // 建议JVM进行垃圾回收(不保证立即执行)
        System.gc();
    }
}
2.2 内存泄漏示例
public class MemoryLeakDemo {
    private static List<byte[]> list = new ArrayList<>();
    
    public static void potentialMemoryLeak() {
        while (true) {
            // 创建1MB的对象并保持引用
            byte[] data = new byte[1024 * 1024];
            list.add(data);
            
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

3. 内存优化

3.1 对象池化示例
public class ObjectPoolDemo {
    private static final int POOL_SIZE = 10;
    private static final Queue<StringBuilder> stringBuilderPool = 
        new ArrayBlockingQueue<>(POOL_SIZE);
    
    public static StringBuilder acquireStringBuilder() {
        StringBuilder sb = stringBuilderPool.poll();
        if (sb == null) {
            sb = new StringBuilder();
        }
        return sb;
    }
    
    public static void releaseStringBuilder(StringBuilder sb) {
        sb.setLength(0);  // 清空内容
        stringBuilderPool.offer(sb);
    }
}
3.2 JVM参数调优
# 设置堆内存大小
java -Xms1g -Xmx2g MyApplication

# 设置新生代大小
java -XX:NewSize=256m -XX:MaxNewSize=256m MyApplication

# 设置垃圾回收器
java -XX:+UseG1GC MyApplication

# 打印GC日志
java -XX:+PrintGCDetails -XX:+PrintGCDateStamps MyApplication

第五章 常用类库

1. java.lang包

1.1 Object类

Object是所有类的父类,提供了一些基本方法:

public class ObjectDemo {
    public static void main(String[] args) {
        Person person = new Person("张三", 25);
        
        // equals方法
        Person anotherPerson = new Person("张三", 25);
        System.out.println(person.equals(anotherPerson));  // 需要重写equals
        
        // hashCode方法
        System.out.println(person.hashCode());
        
        // toString方法
        System.out.println(person.toString());
    }
}

class Person {
    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Person person = (Person) obj;
        return age == person.age && Objects.equals(name, person.name);
    }
    
    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
    
    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}
1.2 包装类

基本数据类型的包装类:

public class WrapperClassDemo {
    public static void main(String[] args) {
        // 自动装箱
        Integer num1 = 100;
        Double num2 = 3.14;
        
        // 自动拆箱
        int n1 = num1;
        double n2 = num2;
        
        // 字符串转换
        int parsed1 = Integer.parseInt("123");
        double parsed2 = Double.parseDouble("3.14");
        
        // 值比较
        Integer a = 127;
        Integer b = 127;
        System.out.println(a == b);      // true(-128到127缓存)
        Integer c = 128;
        Integer d = 128;
        System.out.println(c == d);      // false
        System.out.println(c.equals(d)); // true
    }
}

2. java.util包

2.1 集合框架
public class CollectionDemo {
    public static void main(String[] args) {
        // List示例
        List<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");
        
        // Set示例
        Set<Integer> set = new HashSet<>();
        set.add(1);
        set.add(2);
        set.add(1);  // 重复元素不会被添加
        
        // Map示例
        Map<String, Integer> map = new HashMap<>();
        map.put("A", 1);
        map.put("B", 2);
        map.put("C", 3);
        
        // 遍历示例
        for (String fruit : list) {
            System.out.println(fruit);
        }
        
        map.forEach((key, value) -> 
            System.out.println(key + ": " + value));
    }
}
2.2 日期时间API
public class DateTimeDemo {
    public static void main(String[] args) {
        // 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println("当前时间:" + now);
        
        // 日期计算
        LocalDate today = LocalDate.now();
        LocalDate nextWeek = today.plusWeeks(1);
        
        // 格式化
        DateTimeFormatter formatter = 
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formatted = now.format(formatter);
        
        // 解析
        LocalDateTime parsed = 
            LocalDateTime.parse("2024-01-01 12:00:00", formatter);
    }
}

3. 字符串处理

3.1 String类操作
public class StringDemo {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "World";
        
        // 字符串连接
        String result = str1 + " " + str2;
        
        // 常用方法
        System.out.println(result.length());        // 长度
        System.out.println(result.charAt(0));       // 获取字符
        System.out.println(result.substring(0, 5)); // 子串
        System.out.println(result.indexOf("o"));    // 查找
        
        // 分割
        String text = "apple,banana,orange";
        String[] fruits = text.split(",");
        
        // 替换
        String replaced = text.replace(",", ";");
    }
}
3.2 StringBuilder和StringBuffer
public class StringBuilderDemo {
    public static void main(String[] args) {
        // StringBuilder(非线程安全,但性能更好)
        StringBuilder builder = new StringBuilder();
        builder.append("Hello")
               .append(" ")
               .append("World");
        System.out.println(builder.toString());
        
        // StringBuffer(线程安全)
        StringBuffer buffer = new StringBuffer();
        buffer.append("Java")
              .append(" is ")
              .append("awesome");
        System.out.println(buffer.toString());
        
        // 性能比较
        long startTime = System.currentTimeMillis();
        String str = "";
        for (int i = 0; i < 10000; i++) {
            str += "a";  // 性能很差
        }
        System.out.println("String耗时:" + 
            (System.currentTimeMillis() - startTime));
        
        startTime = System.currentTimeMillis();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 10000; i++) {
            sb.append("a");  // 性能好
        }
        System.out.println("StringBuilder耗时:" + 
            (System.currentTimeMillis() - startTime));
    }
}

第六章 输入输出(I/O)

1. I/O流概述

1.1 I/O流分类
Java I/O流
├── 字节流(Byte Streams)
│   ├── InputStream
│   │   ├── FileInputStream
│   │   ├── BufferedInputStream
│   │   └── ByteArrayInputStream
│   └── OutputStream
│       ├── FileOutputStream
│       ├── BufferedOutputStream
│       └── ByteArrayOutputStream
└── 字符流(Character Streams)
    ├── Reader
    │   ├── FileReader
    │   ├── BufferedReader
    │   └── InputStreamReader
    └── Writer
        ├── FileWriter
        ├── BufferedWriter
        └── OutputStreamWriter

2. 文件操作

2.1 基本文件操作
public class FileOperationDemo {
    public static void main(String[] args) {
        // 创建文件
        File file = new File("test.txt");
        try {
            if (file.createNewFile()) {
                System.out.println("文件创建成功");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        // 文件信息
        System.out.println("文件名:" + file.getName());
        System.out.println("文件路径:" + file.getPath());
        System.out.println("文件大小:" + file.length());
        System.out.println("是否可读:" + file.canRead());
        System.out.println("是否可写:" + file.canWrite());
    }
}
2.2 文件读写操作
public class FileReadWriteDemo {
    // 写入文件
    public static void writeFile() {
        try (FileWriter writer = new FileWriter("output.txt")) {
            writer.write("Hello, Java I/O!\n");
            writer.write("这是第二行内容");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    // 读取文件
    public static void readFile() {
        try (BufferedReader reader = new BufferedReader(
                new FileReader("output.txt"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
2.3 文件复制工具
public class FileCopyUtil {
    // 使用缓冲流复制文件
    public static void copyFile(String source, String target) {
        try (BufferedInputStream bis = new BufferedInputStream(
                new FileInputStream(source));
             BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(target))) {
            
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    // 使用NIO复制文件
    public static void copyFileNIO(String source, String target) {
        try {
            Path sourcePath = Paths.get(source);
            Path targetPath = Paths.get(target);
            Files.copy(sourcePath, targetPath, 
                StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. I/O工具类

3.1 文本文件处理工具
public class TextFileUtil {
    // 读取文本文件
    public static String readTextFile(String path, String charset) 
            throws IOException {
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(
                    new FileInputStream(path), charset))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
        }
        return content.toString();
    }
    
    // 写入文本文件
    public static void writeTextFile(String path, String content, 
            String charset) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(
                    new FileOutputStream(path), charset))) {
            writer.write(content);
        }
    }
}

第七章 多线程编程

1. 线程基础

1.1 线程的创建方式
// 1. 继承Thread类
public class ThreadDemo1 extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() 
                + " - 计数: " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ThreadDemo1 thread1 = new ThreadDemo1();
        ThreadDemo1 thread2 = new ThreadDemo1();
        
        thread1.setName("线程1");
        thread2.setName("线程2");
        
        thread1.start();
        thread2.start();
    }
}

// 2. 实现Runnable接口
public class RunnableDemo implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() 
                + " - 计数: " + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        RunnableDemo runnable = new RunnableDemo();
        
        Thread thread1 = new Thread(runnable, "线程1");
        Thread thread2 = new Thread(runnable, "线程2");
        
        thread1.start();
        thread2.start();
    }
}

// 3. 使用Lambda表达式(Java 8+)
public class LambdaThreadDemo {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() 
                    + " - 计数: " + i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "Lambda线程");
        
        thread.start();
    }
}
1.2 线程生命周期
public class ThreadLifecycleDemo {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                // 运行状态
                System.out.println("线程运行中...");
                Thread.sleep(2000);  // 阻塞状态
                System.out.println("线程恢复运行...");
            } catch (InterruptedException e) {
                System.out.println("线程被中断...");
            }
        });
        
        System.out.println("线程状态:" + thread.getState());  // NEW
        
        thread.start();  // RUNNABLE
        System.out.println("线程状态:" + thread.getState());
        
        Thread.sleep(1000);
        System.out.println("线程状态:" + thread.getState());  // TIMED_WAITING
        
        thread.join();  // 等待线程结束
        System.out.println("线程状态:" + thread.getState());  // TERMINATED
    }
}

2. 线程控制

2.1 线程同步
public class SynchronizedDemo {
    private int count = 0;
    
    // 同步方法
    public synchronized void increment() {
        count++;
    }
    
    // 同步代码块
    public void incrementBlock() {
        synchronized(this) {
            count++;
        }
    }
    
    // 使用Lock接口
    private final Lock lock = new ReentrantLock();
    
    public void incrementLock() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }
}
2.2 线程通信
public class ProducerConsumerDemo {
    private static class SharedResource {
        private String message;
        private boolean hasMessage = false;
        
        public synchronized void produce(String message) 
                throws InterruptedException {
            while (hasMessage) {
                wait();  // 等待消费者消费
            }
            this.message = message;
            hasMessage = true;
            System.out.println("生产: " + message);
            notify();  // 通知消费者
        }
        
        public synchronized String consume() 
                throws InterruptedException {
            while (!hasMessage) {
                wait();  // 等待生产者生产
            }
            String message = this.message;
            hasMessage = false;
            System.out.println("消费: " + message);
            notify();  // 通知生产者
            return message;
        }
    }
    
    public static void main(String[] args) {
        SharedResource resource = new SharedResource();
        
        // 生产者线程
        Thread producer = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    resource.produce("消息-" + i);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        
        // 消费者线程
        Thread consumer = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    resource.consume();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        
        producer.start();
        consumer.start();
    }
}

第八章 设计模式

1. 创建型模式

1.1 单例模式(Singleton Pattern)
// 1. 懒汉式单例(线程安全版本)
public class LazySingleton {
    private static volatile LazySingleton instance;
    
    private LazySingleton() {}
    
    public static LazySingleton getInstance() {
        if (instance == null) {
            synchronized (LazySingleton.class) {
                if (instance == null) {
                    instance = new LazySingleton();
                }
            }
        }
        return instance;
    }
}

// 2. 饿汉式单例
public class EagerSingleton {
    private static final EagerSingleton instance = new EagerSingleton();
    
    private EagerSingleton() {}
    
    public static EagerSingleton getInstance() {
        return instance;
    }
}

// 3. 枚举单例(最佳实践)
public enum EnumSingleton {
    INSTANCE;
    
    private String data;
    
    public String getData() {
        return data;
    }
    
    public void setData(String data) {
        this.data = data;
    }
}
1.2 工厂模式(Factory Pattern)
// 简单工厂模式
interface Product {
    void operation();
}

class ConcreteProductA implements Product {
    @Override
    public void operation() {
        System.out.println("具体产品A的操作");
    }
}

class ConcreteProductB implements Product {
    @Override
    public void operation() {
        System.out.println("具体产品B的操作");
    }
}

class SimpleFactory {
    public static Product createProduct(String type) {
        if ("A".equals(type)) {
            return new ConcreteProductA();
        } else if ("B".equals(type)) {
            return new ConcreteProductB();
        }
        throw new IllegalArgumentException("未知产品类型");
    }
}

2. 行为型模式

2.1 观察者模式(Observer Pattern)
// 观察者接口
interface Observer {
    void update(String message);
}

// 具体观察者
class ConcreteObserver implements Observer {
    private String name;
    
    public ConcreteObserver(String name) {
        this.name = name;
    }
    
    @Override
    public void update(String message) {
        System.out.println(name + "收到消息:" + message);
    }
}

// 主题(被观察者)
class Subject {
    private List<Observer> observers = new ArrayList<>();
    
    public void attach(Observer observer) {
        observers.add(observer);
    }
    
    public void detach(Observer observer) {
        observers.remove(observer);
    }
    
    public void notifyObservers(String message) {
        for (Observer observer : observers) {
            observer.update(message);
        }
    }
}
2.2 策略模式(Strategy Pattern)
// 策略接口
interface PaymentStrategy {
    void pay(int amount);
}

// 具体策略
class CreditCardPayment implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        System.out.println("使用信用卡支付:" + amount);
    }
}

class AlipayPayment implements PaymentStrategy {
    @Override
    public void pay(int amount) {
        System.out.println("使用支付宝支付:" + amount);
    }
}

// 上下文
class PaymentContext {
    private PaymentStrategy strategy;
    
    public PaymentContext(PaymentStrategy strategy) {
        this.strategy = strategy;
    }
    
    public void executePayment(int amount) {
        strategy.pay(amount);
    }
}

3. 结构型模式

3.1 适配器模式(Adapter Pattern)
// 目标接口
interface Target {
    void request();
}

// 需要适配的类
class Adaptee {
    public void specificRequest() {
        System.out.println("适配者的特殊请求");
    }
}

// 适配器
class Adapter implements Target {
    private Adaptee adaptee;
    
    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }
    
    @Override
    public void request() {
        adaptee.specificRequest();
    }
}

4. 设计模式最佳实践

  1. 设计原则:

    • 单一职责原则:一个类只负责一项功能
    • 开放封闭原则:对扩展开放,对修改关闭
    • 依赖倒置原则:依赖抽象而不是具体实现
    • 接口隔离原则:使用多个专门的接口而不是单个总接口
    • 里氏替换原则:子类必须能够替换父类
  2. 模式选择建议:

    • 优先使用组合而不是继承
    • 针对接口编程而不是具体实现
    • 只在必要时使用设计模式
    • 保持设计的简单性
  3. 常见应用场景:

    • 单例模式:配置管理、线程池、缓存
    • 工厂模式:对象创建、数据库连接
    • 观察者模式:事件处理、消息通知
    • 策略模式:算法族、业务规则
    • 适配器模式:接口转换、兼容性处理

总结

本教程系统地介绍了Java编程的核心知识,从基础语法到高级特性,包括:

  1. Java基础语法和面向对象编程
  2. 异常处理和内存管理
  3. 常用类库和I/O操作
  4. 多线程编程
  5. 设计模式的应用

通过学习这些内容,读者可以掌握Java开发的核心技能,为进一步深入学习打下坚实基础。

🎉 恭喜你!如果你看到了这里,说明你已经完成了Java基础的第一次探索之旅!相信你已经对Java的核心知识有了一个清晰的认识。记住,编程学习是一个循序渐进的过程,就像搭建乐高一样,今天学的每一个知识点都是你未来编程大厦中重要的一块基石。

💪 如果你觉得有些概念还不太清楚,不要着急,这很正常!建议你:

  1. 先收藏本文,随时可以回来查看
  2. 动手练习文中的代码示例
  3. 遇到问题多去实践,多去探索

🌟 最后,如果这篇文章对你有帮助,别忘了点个赞!我们下期再见!

📝 有任何问题都可以在评论区留言,我会及时回复!

参考资料

  1. 《Java核心技术》
  2. 《Effective Java》
  3. 《设计模式:可复用面向对象软件的基础》
  4. 《Java并发编程实战》
  5. Java官方文档
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值