Java相关

20 minute read

Java 编程语言 完整系统学习大纲


一、Java 语言概述

1.1 Java 发展历史

  • 1991年:James Gosling 领导的 Green 项目,最初名为 Oak
  • 1995年:正式更名为 Java,发布 Java 1.0
  • 1998年:Java 2 平台发布,包含 J2SE、J2EE、J2ME
  • 2004年:Java 5 发布,重要更新(泛型、注解、自动装箱等)
  • 2011年:Oracle 收购 Sun 公司
  • 2014年:Java 8 发布,引入 Lambda 表达式
  • 2017年:Java 9 发布,模块化系统
  • 2018年:Java 发布周期改为每半年一次
  • 2021年:Java 17 发布,长期支持版本

1.2 Java 技术体系

  1. Java SE (Standard Edition)
    • 核心 API,基础语法
    • 标准库,GUI 编程
  2. Java EE (Enterprise Edition)
    • 企业级应用开发
    • Web 应用,分布式系统
  3. Java ME (Micro Edition)
    • 嵌入式设备,移动设备

1.3 Java 核心特性

  • 简单性:语法简洁,类似 C/C++
  • 面向对象:完全面向对象
  • 平台无关性:一次编写,到处运行
  • 安全性:字节码验证,安全管理器
  • 多线程:内置多线程支持
  • 动态性:运行时加载类
  • 分布式:网络编程能力强大
  • 健壮性:异常处理,垃圾回收

1.4 JVM、JRE、JDK

  • JVM (Java Virtual Machine)
    • Java 虚拟机,执行字节码
    • 平台相关,不同系统有不同实现
  • JRE (Java Runtime Environment)
    • Java 运行环境
    • 包含 JVM 和核心类库
  • JDK (Java Development Kit)
    • Java 开发工具包
    • 包含 JRE 和开发工具
# 检查 Java 版本
java -version
javac -version

# 设置环境变量
# Windows: 设置 JAVA_HOME=C:\Program Files\Java\jdk-17
# Linux/Mac: export JAVA_HOME=/usr/lib/jvm/java-17-openjdk

二、Java 开发环境搭建

2.1 安装与配置

  1. 下载安装
    • 官网下载对应平台 JDK
    • 设置环境变量 JAVA_HOME
    • 添加 PATH
    # Windows
    setx JAVA_HOME "C:\Program Files\Java\jdk-17"
    setx PATH "%PATH%;%JAVA_HOME%\bin"
    
    # Linux/Mac
    export JAVA_HOME=/usr/lib/jvm/java-17-openjdk
    export PATH=$PATH:$JAVA_HOME/bin
    
  2. 开发工具
    • IDE:IntelliJ IDEA、Eclipse、NetBeans
    • 构建工具:Maven、Gradle
    • 版本控制:Git

2.2 第一个 Java 程序

// HelloWorld.java
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
# 编译
javac HelloWorld.java

# 运行
java HelloWorld

2.3 Java 程序结构

// 包声明
package com.example.demo;

// 导入语句
import java.util.Scanner;
import java.util.*;

// 类定义
public class Main {
    // 主方法
    public static void main(String[] args) {
        // 代码逻辑
    }
}

三、Java 基础语法

3.1 标识符与关键字

  • 标识符规则
    • 字母、数字、下划线、美元符号
    • 不能以数字开头
    • 不能是关键字
    • 区分大小写
  • 关键字
    • class, public, static, void
    • int, boolean, if, else
    • for, while, do, switch
    • new, this, super, instanceof
    • try, catch, finally, throw
    • abstract, interface, extends, implements

3.2 数据类型

  1. 基本数据类型
    • 整数:byte(1), short(2), int(4), long(8)
    • 浮点:float(4), double(8)
    • 字符:char(2)
    • 布尔:boolean(1)
    // 基本数据类型
    byte b = 127;           // 1字节
    short s = 32767;        // 2字节
    int i = 2147483647;     // 4字节
    long l = 9223372036854775807L;  // 8字节
    float f = 3.14f;        // 4字节
    double d = 3.1415926;   // 8字节
    char c = 'A';           // 2字节
    boolean flag = true;    // 1字节
    
  2. 引用数据类型
    • 接口
    • 数组
    • 枚举
  3. 类型转换
    • 自动转换:小范围转大范围
    • 强制转换:大范围转小范围
    // 自动类型转换
    int a = 100;
    double b = a;  // 自动转换
    
    // 强制类型转换
    double x = 9.78;
    int y = (int) x;  // 强制转换,结果为9
    

3.3 变量与常量

// 变量声明
int age;
String name;

// 变量初始化
age = 25;
name = "张三";

// 声明并初始化
int count = 10;
double price = 9.99;

// 常量
final double PI = 3.14159;
final int MAX_SIZE = 100;

3.4 运算符

  1. 算术运算符:+ - * / % ++ –
  2. 关系运算符:== != > < >= <=
  3. 逻辑运算符:&&   !
  4. 位运算符:& ^ ~ « » »>
  5. 赋值运算符:= += -= *= /= %=
  6. 三元运算符:? :
int a = 10, b = 20;

// 算术运算
int sum = a + b;
int diff = a - b;
int product = a * b;
int quotient = b / a;
int remainder = b % a;

// 关系运算
boolean isEqual = (a == b);
boolean isGreater = (a > b);

// 逻辑运算
boolean result = (a > 5) && (b < 30);

// 位运算
int bitwiseAnd = a & b;
int leftShift = a << 2;  // 40

// 三元运算
int max = (a > b) ? a : b;

3.5 控制语句

  1. 条件语句

    // if-else
    int score = 85;
    if (score >= 90) {
        System.out.println("优秀");
    } else if (score >= 80) {
        System.out.println("良好");
    } else {
        System.out.println("继续努力");
    }
    
    // switch
    int day = 3;
    switch (day) {
        case 1:
            System.out.println("星期一");
            break;
        case 2:
            System.out.println("星期二");
            break;
        default:
            System.out.println("其他");
    }
    
  2. 循环语句

    // for循环
    for (int i = 0; i < 5; i++) {
        System.out.println(i);
    }
    
    // 增强for循环
    int[] numbers = {1, 2, 3, 4, 5};
    for (int num : numbers) {
        System.out.println(num);
    }
    
    // while循环
    int count = 0;
    while (count < 5) {
        System.out.println(count);
        count++;
    }
    
    // do-while循环
    int i = 0;
    do {
        System.out.println(i);
        i++;
    } while (i < 5);
    
  3. 跳转语句

    • break
    • continue
    • return
    // break
    for (int i = 0; i < 10; i++) {
        if (i == 5) {
            break;  // 跳出循环
        }
        System.out.println(i);
    }
    
    // continue
    for (int i = 0; i < 10; i++) {
        if (i % 2 == 0) {
            continue;  // 跳过本次循环
        }
        System.out.println(i);
    }
    

3.6 数组

// 一维数组
int[] arr1 = new int[5];  // 声明
int[] arr2 = {1, 2, 3, 4, 5};  // 声明并初始化

// 访问元素
arr1[0] = 10;
int value = arr2[2];

// 遍历数组
for (int i = 0; i < arr2.length; i++) {
    System.out.println(arr2[i]);
}

// 多维数组
int[][] matrix = new int[3][3];
int[][] jaggedArray = {{1, 2}, {3, 4, 5}, {6}};

// 遍历多维数组
for (int i = 0; i < jaggedArray.length; i++) {
    for (int j = 0; j < jaggedArray[i].length; j++) {
        System.out.print(jaggedArray[i][j] + " ");
    }
    System.out.println();
}

四、面向对象编程

4.1 类与对象

// 定义类
public class Person {
    // 属性(成员变量)
    private String name;
    private int age;
    
    // 构造方法
    public Person() {
        this.name = "Unknown";
        this.age = 0;
    }
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    // 方法
    public void setName(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
    
    public void setAge(int age) {
        if (age >= 0 && age <= 150) {
            this.age = age;
        }
    }
    
    public int getAge() {
        return age;
    }
    
    public void introduce() {
        System.out.println("我叫" + name + ",今年" + age + "岁。");
    }
}

// 创建对象
Person p1 = new Person();
Person p2 = new Person("张三", 25);
p2.introduce();

4.2 构造方法

  • 默认构造方法:无参构造
  • 有参构造方法:带参数
  • 构造方法重载:多个构造方法
  • this关键字:引用当前对象
public class Student {
    private String name;
    private int id;
    
    // 默认构造方法
    public Student() {
        this("Unknown", 0);
    }
    
    // 有参构造方法
    public Student(String name) {
        this(name, 0);
    }
    
    // 有参构造方法
    public Student(String name, int id) {
        this.name = name;
        this.id = id;
    }
    
    // 使用this调用其他构造方法
    public Student(int id) {
        this();  // 调用无参构造
        this.id = id;
    }
}

4.3 访问修饰符

  • private:仅本类可见
  • default:同包可见
  • protected:同包及子类可见
  • public:所有类可见
package com.example;

public class AccessExample {
    private int privateVar = 1;      // 仅本类
    int defaultVar = 2;              // 同包
    protected int protectedVar = 3;  // 同包+子类
    public int publicVar = 4;        // 所有类
}

4.4 继承

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

// 子类
class Dog extends Animal {
    private String breed;
    
    public Dog(String name, String breed) {
        super(name);  // 调用父类构造方法
        this.breed = breed;
    }
    
    // 重写父类方法
    @Override
    public void eat() {
        System.out.println(getName() + "(" + breed + ")正在吃狗粮");
    }
    
    // 子类特有方法
    public void bark() {
        System.out.println("汪汪汪!");
    }
}

// 测试
Dog dog = new Dog("旺财", "金毛");
dog.eat();     // 调用重写的方法
dog.sleep();   // 调用继承的方法
dog.bark();    // 调用子类特有方法

4.5 多态

// 父类
class Shape {
    public void draw() {
        System.out.println("绘制形状");
    }
    
    public double getArea() {
        return 0;
    }
}

// 子类
class Circle extends Shape {
    private double radius;
    
    public Circle(double radius) {
        this.radius = radius;
    }
    
    @Override
    public void draw() {
        System.out.println("绘制圆形,半径:" + radius);
    }
    
    @Override
    public double getArea() {
        return Math.PI * radius * radius;
    }
}

class Rectangle extends Shape {
    private double width;
    private double height;
    
    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }
    
    @Override
    public void draw() {
        System.out.println("绘制矩形,宽:" + width + ",高:" + height);
    }
    
    @Override
    public double getArea() {
        return width * height;
    }
}

// 测试多态
Shape[] shapes = new Shape[2];
shapes[0] = new Circle(5.0);
shapes[1] = new Rectangle(4.0, 6.0);

for (Shape shape : shapes) {
    shape.draw();  // 多态调用
    System.out.println("面积:" + shape.getArea());
}

4.6 抽象类与接口

  1. 抽象类

    // 抽象类
    abstract class Animal {
        protected String name;
            
        public Animal(String name) {
            this.name = name;
        }
            
        // 抽象方法
        public abstract void makeSound();
            
        // 具体方法
        public void sleep() {
            System.out.println(name + "正在睡觉");
        }
    }
    
    // 实现抽象类
    class Cat extends Animal {
        public Cat(String name) {
            super(name);
        }
            
        @Override
        public void makeSound() {
            System.out.println(name + "说:喵喵喵");
        }
    }
    
  2. 接口

    // 接口
    interface Swimmable {
        // 默认是 public abstract
        void swim();
            
        // 默认方法(Java 8+)
        default void dive() {
            System.out.println("正在下潜");
        }
            
        // 静态方法(Java 8+)
        static void showAbility() {
            System.out.println("我会游泳");
        }
            
        // 私有方法(Java 9+)
        private void privateMethod() {
            System.out.println("私有方法");
        }
    }
    
    interface Flyable {
        void fly();
    }
    
    // 实现接口
    class Duck implements Swimmable, Flyable {
        @Override
        public void swim() {
            System.out.println("鸭子在游泳");
        }
            
        @Override
        public void fly() {
            System.out.println("鸭子在飞翔");
        }
    }
    

4.7 内部类

  1. 成员内部类

    class Outer {
        private int outerValue = 10;
            
        class Inner {
            public void print() {
                System.out.println("外部类变量:" + outerValue);
            }
        }
    }
    
    // 使用
    Outer outer = new Outer();
    Outer.Inner inner = outer.new Inner();
    inner.print();
    
  2. 静态内部类

    class Outer {
        private static int staticValue = 20;
            
        static class StaticInner {
            public void print() {
                System.out.println("静态变量:" + staticValue);
            }
        }
    }
    
  3. 局部内部类

    class Outer {
        public void method() {
            class LocalInner {
                public void print() {
                    System.out.println("局部内部类");
                }
            }
                
            LocalInner inner = new LocalInner();
            inner.print();
        }
    }
    
  4. 匿名内部类

    interface Greeting {
        void sayHello();
    }
    
    Greeting greeting = new Greeting() {
        @Override
        public void sayHello() {
            System.out.println("Hello!");
        }
    };
    

4.8 枚举

// 枚举定义
enum Day {
    MONDAY("星期一"),
    TUESDAY("星期二"),
    WEDNESDAY("星期三"),
    THURSDAY("星期四"),
    FRIDAY("星期五"),
    SATURDAY("星期六"),
    SUNDAY("星期日");
    
    private String chinese;
    
    // 枚举构造方法
    Day(String chinese) {
        this.chinese = chinese;
    }
    
    public String getChinese() {
        return chinese;
    }
}

// 使用枚举
Day today = Day.MONDAY;
System.out.println(today);              // MONDAY
System.out.println(today.getChinese()); // 星期一
System.out.println(today.ordinal());    // 0(序号)

// switch中使用枚举
switch (today) {
    case MONDAY:
        System.out.println("周一工作日");
        break;
    case SATURDAY:
    case SUNDAY:
        System.out.println("周末休息");
        break;
    default:
        System.out.println("工作日");
}

4.9 注解

// 自定义注解
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
    String value() default "";
    int count() default 0;
    String[] tags() default {};
}

// 使用注解
@MyAnnotation(value = "测试", count = 5, tags = {"java", "annotation"})
class MyClass {
    @MyAnnotation("方法注解")
    public void myMethod() {
        // 方法体
    }
    
    @Deprecated
    public void oldMethod() {
        // 过时的方法
    }
    
    @Override
    public String toString() {
        return "MyClass";
    }
}

4.10 泛型

// 泛型类
class Box<T> {
    private T content;
    
    public Box(T content) {
        this.content = content;
    }
    
    public T getContent() {
        return content;
    }
    
    public void setContent(T content) {
        this.content = content;
    }
    
    // 泛型方法
    public <E> void printType(E element) {
        System.out.println(element.getClass().getName());
    }
}

// 使用泛型
Box<String> stringBox = new Box<>("Hello");
Box<Integer> intBox = new Box<>(100);

// 通配符
List<? extends Number> numbers1;  // 上限通配符
List<? super Integer> numbers2;   // 下限通配符

五、异常处理

5.1 异常体系

  • Throwable
    • Error:系统错误,程序无法处理
    • Exception
      • RuntimeException:运行时异常
      • IOException:IO异常
      • SQLException:SQL异常

5.2 异常处理机制

try {
    // 可能抛出异常的代码
    int result = 10 / 0;
} catch (ArithmeticException e) {
    // 处理算术异常
    System.out.println("除数不能为零");
} catch (Exception e) {
    // 处理其他异常
    System.out.println("发生异常:" + e.getMessage());
} finally {
    // 无论是否发生异常都会执行
    System.out.println("清理资源");
}

5.3 自定义异常

// 自定义异常类
class MyException extends Exception {
    public MyException() {
        super();
    }
    
    public MyException(String message) {
        super(message);
    }
    
    public MyException(String message, Throwable cause) {
        super(message, cause);
    }
}

// 使用自定义异常
void validate(int value) throws MyException {
    if (value < 0) {
        throw new MyException("值不能为负数");
    }
}

try {
    validate(-5);
} catch (MyException e) {
    System.out.println("捕获自定义异常:" + e.getMessage());
}

5.4 try-with-resources

// 实现AutoCloseable接口的资源类
class MyResource implements AutoCloseable {
    public void doSomething() {
        System.out.println("执行操作");
    }
    
    @Override
    public void close() {
        System.out.println("资源已关闭");
    }
}

// 自动关闭资源
try (MyResource resource = new MyResource()) {
    resource.doSomething();
} catch (Exception e) {
    e.printStackTrace();
}
// 不需要显式调用close(),资源会自动关闭

六、集合框架

6.1 集合体系

  • Collection 接口
    • List:有序,可重复
      • ArrayList
      • LinkedList
      • Vector
    • Set:无序,不可重复
      • HashSet
      • LinkedHashSet
      • TreeSet
    • Queue:队列
      • LinkedList
      • PriorityQueue
  • Map 接口
    • HashMap
    • LinkedHashMap
    • TreeMap
    • Hashtable

6.2 List

// ArrayList
List<String> arrayList = new ArrayList<>();
arrayList.add("苹果");
arrayList.add("香蕉");
arrayList.add("橙子");
System.out.println(arrayList.get(0));  // 苹果

// LinkedList
List<String> linkedList = new LinkedList<>();
linkedList.add("A");
linkedList.add("B");
linkedList.addFirst("First");
linkedList.addLast("Last");

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

// 迭代器
Iterator<String> iterator = arrayList.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

6.3 Set

// HashSet
Set<String> hashSet = new HashSet<>();
hashSet.add("苹果");
hashSet.add("香蕉");
hashSet.add("苹果");  // 重复元素不会添加
System.out.println(hashSet.size());  // 2

// LinkedHashSet(保持插入顺序)
Set<String> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add("苹果");
linkedHashSet.add("香蕉");
linkedHashSet.add("橙子");

// TreeSet(排序)
Set<String> treeSet = new TreeSet<>();
treeSet.add("banana");
treeSet.add("apple");
treeSet.add("cherry");
// 会自动排序:apple, banana, cherry

6.4 Map

// HashMap
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("苹果", 10);
hashMap.put("香蕉", 5);
hashMap.put("橙子", 8);

// 获取值
Integer apples = hashMap.get("苹果");  // 10
Integer oranges = hashMap.getOrDefault("橙子", 0);  // 8

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

// LinkedHashMap(保持插入顺序)
Map<String, Integer> linkedHashMap = new LinkedHashMap<>();

// TreeMap(按键排序)
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("banana", 5);
treeMap.put("apple", 10);
treeMap.put("cherry", 8);
// 按键排序:apple, banana, cherry

6.5 集合工具类

// Collections工具类
List<Integer> numbers = new ArrayList<>();
numbers.add(3);
numbers.add(1);
numbers.add(4);
numbers.add(1);
numbers.add(5);

// 排序
Collections.sort(numbers);

// 反转
Collections.reverse(numbers);

// 打乱顺序
Collections.shuffle(numbers);

// 查找
int index = Collections.binarySearch(numbers, 4);

// 不可修改集合
List<Integer> unmodifiableList = Collections.unmodifiableList(numbers);

// Arrays工具类
int[] arr = {1, 2, 3, 4, 5};
String str = Arrays.toString(arr);  // 数组转字符串
Arrays.sort(arr);                   // 排序
int index = Arrays.binarySearch(arr, 3);  // 二分查找

七、输入输出(I/O)

7.1 流的概念

  • 字节流
    • InputStream / OutputStream
  • 字符流
    • Reader / Writer
  • 节点流
    • 直接连接数据源
  • 处理流
    • 包装其他流,增加功能

7.2 文件操作

// 文件操作
File file = new File("test.txt");
System.out.println("文件是否存在:" + file.exists());
System.out.println("文件大小:" + file.length() + "字节");
System.out.println("文件名:" + file.getName());
System.out.println("绝对路径:" + file.getAbsolutePath());

// 创建文件
boolean created = file.createNewFile();

// 删除文件
boolean deleted = file.delete();

// 创建目录
File dir = new File("mydir");
boolean dirCreated = dir.mkdir();

// 列出目录内容
File[] files = dir.listFiles();

7.3 字节流

// 字节输入流
try (FileInputStream fis = new FileInputStream("input.txt")) {
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = fis.read(buffer)) != -1) {
        // 处理读取的数据
    }
} catch (IOException e) {
    e.printStackTrace();
}

// 字节输出流
try (FileOutputStream fos = new FileOutputStream("output.txt")) {
    String data = "Hello, World!";
    fos.write(data.getBytes());
} catch (IOException e) {
    e.printStackTrace();
}

7.4 字符流

// 字符输入流
try (FileReader fr = new FileReader("input.txt");
     BufferedReader br = new BufferedReader(fr)) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

// 字符输出流
try (FileWriter fw = new FileWriter("output.txt");
     BufferedWriter bw = new BufferedWriter(fw)) {
    bw.write("Hello, World!");
    bw.newLine();
    bw.write("这是第二行");
} catch (IOException e) {
    e.printStackTrace();
}

7.5 对象序列化

// 可序列化类
class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private transient int age;  // transient字段不会被序列化
    
    // 构造方法、getter、setter
}

// 序列化对象
try (ObjectOutputStream oos = new ObjectOutputStream(
        new FileOutputStream("person.dat"))) {
    Person person = new Person("张三", 25);
    oos.writeObject(person);
} catch (IOException e) {
    e.printStackTrace();
}

// 反序列化对象
try (ObjectInputStream ois = new ObjectInputStream(
        new FileInputStream("person.dat"))) {
    Person person = (Person) ois.readObject();
    System.out.println(person.getName());  // 张三
} catch (IOException | ClassNotFoundException e) {
    e.printStackTrace();
}

八、多线程

8.1 线程创建

  1. 继承Thread类

    class MyThread extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                System.out.println(getName() + ": " + i);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    // 使用
    MyThread t1 = new MyThread();
    t1.start();
    
  2. 实现Runnable接口

    class MyRunnable implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + ": " + i);
            }
        }
    }
    
    // 使用
    Thread t2 = new Thread(new MyRunnable());
    t2.start();
    
  3. 实现Callable接口

    class MyCallable implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            int sum = 0;
            for (int i = 1; i <= 10; i++) {
                sum += i;
            }
            return sum;
        }
    }
    
    // 使用
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<Integer> future = executor.submit(new MyCallable());
    Integer result = future.get();  // 55
    executor.shutdown();
    

8.2 线程生命周期

  • 新建:new
  • 就绪:start()
  • 运行:获得CPU
  • 阻塞:sleep()、wait()、IO
  • 死亡:run()结束

8.3 线程同步

  1. synchronized

    class Counter {
        private int count = 0;
            
        // 同步方法
        public synchronized void increment() {
            count++;
        }
            
        // 同步代码块
        public void decrement() {
            synchronized (this) {
                count--;
            }
        }
    }
    
  2. Lock

    class SafeCounter {
        private int count = 0;
        private Lock lock = new ReentrantLock();
            
        public void increment() {
            lock.lock();
            try {
                count++;
            } finally {
                lock.unlock();
            }
        }
    }
    

8.4 线程通信

class SharedResource {
    private boolean available = false;
    
    public synchronized void produce() throws InterruptedException {
        while (available) {
            wait();  // 等待消费
        }
        System.out.println("生产");
        available = true;
        notifyAll();  // 通知消费者
    }
    
    public synchronized void consume() throws InterruptedException {
        while (!available) {
            wait();  // 等待生产
        }
        System.out.println("消费");
        available = false;
        notifyAll();  // 通知生产者
    }
}

8.5 线程池

// 创建线程池
ExecutorService threadPool = Executors.newFixedThreadPool(5);

// 提交任务
for (int i = 0; i < 10; i++) {
    int taskId = i;
    threadPool.execute(() -> {
        System.out.println("执行任务 " + taskId + ",线程:" + 
                          Thread.currentThread().getName());
    });
}

// 关闭线程池
threadPool.shutdown();

8.6 并发集合

// 并发集合
ConcurrentHashMap<String, Integer> concurrentMap = new ConcurrentHashMap<>();
CopyOnWriteArrayList<String> copyOnWriteList = new CopyOnWriteArrayList<>();
BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(10);

九、网络编程

9.1 Socket编程

// 服务器端
try (ServerSocket serverSocket = new ServerSocket(8888)) {
    System.out.println("服务器启动,等待连接...");
    
    while (true) {
        Socket socket = serverSocket.accept();
        new Thread(() -> {
            try (InputStream is = socket.getInputStream();
                 OutputStream os = socket.getOutputStream()) {
                // 处理客户端请求
                byte[] buffer = new byte[1024];
                int length = is.read(buffer);
                String request = new String(buffer, 0, length);
                System.out.println("收到请求:" + request);
                
                // 发送响应
                String response = "Hello, Client!";
                os.write(response.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
} catch (IOException e) {
    e.printStackTrace();
}
// 客户端
try (Socket socket = new Socket("localhost", 8888);
     OutputStream os = socket.getOutputStream();
     InputStream is = socket.getInputStream()) {
    
    // 发送请求
    String request = "Hello, Server!";
    os.write(request.getBytes());
    os.flush();
    
    // 接收响应
    byte[] buffer = new byte[1024];
    int length = is.read(buffer);
    String response = new String(buffer, 0, length);
    System.out.println("收到响应:" + response);
} catch (IOException e) {
    e.printStackTrace();
}

9.2 URL编程

// 读取网页内容
try {
    URL url = new URL("https://www.example.com");
    URLConnection connection = url.openConnection();
    
    try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(connection.getInputStream()))) {
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

9.3 HTTP客户端

// 使用HttpURLConnection
try {
    URL url = new URL("https://api.example.com/data");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setConnectTimeout(5000);
    connection.setReadTimeout(5000);
    
    int responseCode = connection.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream()))) {
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            System.out.println("响应:" + response.toString());
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

十、反射

10.1 获取Class对象

// 三种方式获取Class对象
Class<String> clazz1 = String.class;  // 1. 类名.class

String str = "Hello";
Class<? extends String> clazz2 = str.getClass();  // 2. 对象.getClass()

try {
    Class<?> clazz3 = Class.forName("java.lang.String");  // 3. Class.forName()
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

10.2 反射操作

class Person {
    private String name;
    private int age;
    
    public Person() {}
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public void sayHello() {
        System.out.println("Hello, I'm " + name);
    }
    
    // getter/setter
}

// 反射操作
try {
    // 获取Class对象
    Class<?> clazz = Class.forName("com.example.Person");
    
    // 创建实例
    Object obj1 = clazz.newInstance();  // 无参构造
    Constructor<?> constructor = clazz.getConstructor(String.class, int.class);
    Object obj2 = constructor.newInstance("张三", 25);
    
    // 获取字段
    Field nameField = clazz.getDeclaredField("name");
    nameField.setAccessible(true);  // 访问私有字段
    nameField.set(obj2, "李四");
    
    // 获取方法
    Method sayHelloMethod = clazz.getMethod("sayHello");
    sayHelloMethod.invoke(obj2);
    
    // 获取所有方法
    Method[] methods = clazz.getDeclaredMethods();
    for (Method method : methods) {
        System.out.println(method.getName());
    }
} catch (Exception e) {
    e.printStackTrace();
}

十一、Lambda表达式

11.1 Lambda语法

// 函数式接口
@FunctionalInterface
interface MyInterface {
    void doSomething(String s);
}

// 使用Lambda
MyInterface mi1 = (String s) -> {
    System.out.println(s);
};

// 简化
MyInterface mi2 = s -> System.out.println(s);
mi2.doSomething("Hello Lambda");

11.2 内置函数式接口

// Consumer<T> - 消费型接口
Consumer<String> consumer = s -> System.out.println(s);
consumer.accept("Hello");

// Supplier<T> - 供给型接口
Supplier<String> supplier = () -> "Hello";
String result = supplier.get();

// Function<T, R> - 函数型接口
Function<String, Integer> function = s -> s.length();
int length = function.apply("Hello");

// Predicate<T> - 断言型接口
Predicate<String> predicate = s -> s.length() > 5;
boolean test = predicate.test("Hello");

// BinaryOperator<T> - 二元运算
BinaryOperator<Integer> add = (a, b) -> a + b;
int sum = add.apply(10, 20);

11.3 方法引用

// 静态方法引用
Function<String, Integer> parseInt = Integer::parseInt;
int num = parseInt.apply("123");

// 实例方法引用
String str = "Hello";
Supplier<Integer> length = str::length;
int len = length.get();

// 构造方法引用
Supplier<List<String>> listSupplier = ArrayList::new;
List<String> list = listSupplier.new();

// 任意对象的实例方法
Function<String, String> toUpperCase = String::toUpperCase;
String upper = toUpperCase.apply("hello");

11.4 Stream API

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");

// 创建Stream
Stream<String> stream1 = names.stream();
Stream<String> stream2 = Stream.of("A", "B", "C");

// 中间操作
names.stream()
     .filter(name -> name.length() > 3)  // 过滤
     .map(String::toUpperCase)           // 映射
     .sorted()                           // 排序
     .forEach(System.out::println);      // 终端操作

// 收集结果
List<String> result = names.stream()
    .filter(name -> name.startsWith("A"))
    .collect(Collectors.toList());

// 聚合操作
long count = names.stream().count();
Optional<String> first = names.stream().findFirst();
boolean anyMatch = names.stream().anyMatch(name -> name.startsWith("A"));

// 数值流
IntStream.range(1, 10)  // 1-9
    .filter(n -> n % 2 == 0)
    .forEach(System.out::println);

十二、Java 8+ 新特性

12.1 Java 8

  • Lambda 表达式
  • 函数式接口
  • Stream API
  • 默认方法
  • Optional 类
  • 新的日期时间 API

12.2 Java 9

  • 模块系统
  • 接口私有方法
  • 集合工厂方法
  • 改进的 try-with-resources
// 集合工厂方法
List<String> list = List.of("A", "B", "C");
Set<String> set = Set.of("A", "B", "C");
Map<String, Integer> map = Map.of("A", 1, "B", 2);

12.3 Java 10

  • 局部变量类型推断
var list = new ArrayList<String>();  // 推断为 ArrayList<String>
var map = new HashMap<String, Integer>();
var number = 10;  // 推断为 int

12.4 Java 11

  • 本地变量类型推断增强
  • HTTP Client API
  • 字符串新增方法
// 字符串新方法
String str = "  Hello World  ";
str.isBlank();      // 是否空白
str.strip();        // 去除首尾空白
str.repeat(3);      // 重复
str.lines();        // 行流

12.5 Java 12+

  • Switch 表达式增强
  • Text Blocks
  • Records 类
// Switch表达式
int day = 3;
String dayType = switch (day) {
    case 1, 2, 3, 4, 5 -> "Weekday";
    case 6, 7 -> "Weekend";
    default -> "Invalid";
};

// Text Blocks
String json = """
    {
        "name": "John",
        "age": 30
    }
    """;

// Records
record Person(String name, int age) {}

Person person = new Person("John", 30);
System.out.println(person.name());  // 自动生成getter
System.out.println(person);         // 自动生成toString

十三、数据库编程

13.1 JDBC基础

// 加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");

// 建立连接
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "password";

try (Connection conn = DriverManager.getConnection(url, username, password);
     Statement stmt = conn.createStatement()) {
    
    // 查询
    String sql = "SELECT * FROM users";
    ResultSet rs = stmt.executeQuery(sql);
    
    while (rs.next()) {
        int id = rs.getInt("id");
        String name = rs.getString("name");
        int age = rs.getInt("age");
        System.out.println(id + ", " + name + ", " + age);
    }
    
    // 更新
    String updateSql = "UPDATE users SET age = ? WHERE id = ?";
    try (PreparedStatement pstmt = conn.prepareStatement(updateSql)) {
        pstmt.setInt(1, 30);
        pstmt.setInt(2, 1);
        int rows = pstmt.executeUpdate();
        System.out.println("更新了 " + rows + " 行");
    }
    
} catch (SQLException e) {
    e.printStackTrace();
}

13.2 连接池

// 使用HikariCP连接池
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/test");
config.setUsername("root");
config.setPassword("password");
config.setMaximumPoolSize(10);

try (HikariDataSource dataSource = new HikariDataSource(config);
     Connection conn = dataSource.getConnection()) {
    
    // 使用连接
    // ...
    
} catch (SQLException e) {
    e.printStackTrace();
}

13.3 事务管理

Connection conn = null;
try {
    conn = dataSource.getConnection();
    conn.setAutoCommit(false);  // 开启事务
    
    // 执行多个SQL
    // ...
    
    conn.commit();  // 提交事务
} catch (SQLException e) {
    if (conn != null) {
        try {
            conn.rollback();  // 回滚事务
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    e.printStackTrace();
} finally {
    if (conn != null) {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

十四、JVM与性能调优

14.1 JVM内存结构

  • 程序计数器:当前线程执行的字节码行号
  • Java虚拟机栈:栈帧,局部变量表
  • 本地方法栈:Native方法
  • Java堆:对象实例
  • 方法区:类信息、常量、静态变量
  • 运行时常量池
  • 直接内存

14.2 垃圾回收

  • 新生代
    • Eden区
    • Survivor0区
    • Survivor1区
  • 老年代
  • 垃圾回收算法
    • 标记-清除
    • 复制算法
    • 标记-整理
  • 垃圾收集器
    • Serial
    • Parallel
    • CMS
    • G1
    • ZGC

14.3 性能调优

# JVM参数
java -Xmx2g -Xms2g -Xss256k -XX:+UseG1GC -jar app.jar
  • 堆内存设置
    • -Xms:初始堆大小
    • -Xmx:最大堆大小
  • 垃圾收集器
    • -XX:+UseG1GC
    • -XX:+UseConcMarkSweepGC
  • GC日志
    • -XX:+PrintGCDetails
    • -Xloggc:gc.log

14.4 监控工具

  • jps:查看Java进程
  • jstat:监控JVM统计信息
  • jmap:生成堆转储
  • jstack:生成线程转储
  • jconsole:图形化监控
  • VisualVM:可视化工具
  • JProfiler:商业分析工具

十五、设计模式

15.1 创建型模式

  1. 单例模式

    // 饿汉式
    class Singleton1 {
        private static final Singleton1 INSTANCE = new Singleton1();
            
        private Singleton1() {}
            
        public static Singleton1 getInstance() {
            return INSTANCE;
        }
    }
    
    // 懒汉式(双重检查锁)
    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;
        }
    }
    
    // 静态内部类
    class Singleton3 {
        private Singleton3() {}
            
        private static class Holder {
            private static final Singleton3 INSTANCE = new Singleton3();
        }
            
        public static Singleton3 getInstance() {
            return Holder.INSTANCE;
        }
    }
    
  2. 工厂模式

    // 简单工厂
    interface Shape {
        void draw();
    }
    
    class Circle implements Shape {
        @Override
        public void draw() {
            System.out.println("绘制圆形");
        }
    }
    
    class Square implements Shape {
        @Override
        public void draw() {
            System.out.println("绘制正方形");
        }
    }
    
    class ShapeFactory {
        public static Shape createShape(String type) {
            switch (type) {
                case "circle":
                    return new Circle();
                case "square":
                    return new Square();
                default:
                    throw new IllegalArgumentException("未知类型");
            }
        }
    }
    

15.2 结构型模式

  1. 适配器模式

    // 目标接口
    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();
        }
    }
    

15.3 行为型模式

  1. 观察者模式

    // 观察者接口
    interface Observer {
        void update(String message);
    }
    
    // 主题接口
    interface Subject {
        void registerObserver(Observer observer);
        void removeObserver(Observer observer);
        void notifyObservers();
    }
    
    // 具体主题
    class NewsAgency implements Subject {
        private List<Observer> observers = new ArrayList<>();
        private String news;
            
        @Override
        public void registerObserver(Observer observer) {
            observers.add(observer);
        }
            
        @Override
        public void removeObserver(Observer observer) {
            observers.remove(observer);
        }
            
        @Override
        public void notifyObservers() {
            for (Observer observer : observers) {
                observer.update(news);
            }
        }
            
        public void setNews(String news) {
            this.news = news;
            notifyObservers();
        }
    }
    

十六、框架与工具

16.1 Spring框架

  1. IoC容器
  2. AOP面向切面
  3. Spring MVC
  4. Spring Boot
  5. Spring Cloud

16.2 MyBatis

  1. SQL映射
  2. 动态SQL
  3. 缓存机制

16.3 构建工具

  1. Maven
  2. Gradle

16.4 测试框架

  1. JUnit
  2. Mockito
  3. TestNG

16.5 微服务

  1. Spring Cloud
  2. Dubbo
  3. Kubernetes

十七、学习路线

17.1 入门阶段

  1. Java基础语法
  2. 面向对象编程
  3. 集合框架
  4. 异常处理
  5. I/O流

17.2 进阶阶段

  1. 多线程
  2. 网络编程
  3. 反射
  4. 注解
  5. 泛型

17.3 高级阶段

  1. JVM原理
  2. 性能调优
  3. 设计模式
  4. 并发编程
  5. 分布式

17.4 实战项目

  1. Web应用开发
  2. 微服务架构
  3. 大数据处理
  4. 移动开发
  5. 人工智能

十八、学习资源

18.1 官方文档

18.2 推荐书籍

  1. 《Java核心技术》
  2. 《Effective Java》
  3. 《Java编程思想》
  4. 《深入理解Java虚拟机》
  5. 《Spring实战》

18.3 在线课程

  1. Coursera:Java编程专项
  2. edX:Java课程
  3. 慕课网:Java全栈
  4. 极客时间:Java训练营

18.4 社区论坛

  1. Stack Overflow
  2. GitHub
  3. CSDN
  4. 博客园

18.5 认证考试

  1. Oracle认证
    • OCA
    • OCP
    • OCM
  2. Spring认证
  3. AWS认证

Tags:

Categories:

Updated: