# Java 多线程编程

多线程编程是Java的重要特性之一,能够实现程序的并发执行。

# 线程基础

# 创建线程

// 方式1:继承Thread类
class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("线程正在运行");
    }
}

// 方式2:实现Runnable接口
class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("线程正在运行");
    }
}

// 使用示例
MyThread thread1 = new MyThread();
thread1.start();

Thread thread2 = new Thread(new MyRunnable());
thread2.start();

// 方式3:使用Lambda表达式
Thread thread3 = new Thread(() -> {
    System.out.println("线程正在运行");
});
thread3.start();

# 线程生命周期

  • NEW:新创建的线程
  • RUNNABLE:可运行状态
  • BLOCKED:阻塞状态
  • WAITING:等待状态
  • TIMED_WAITING:超时等待状态
  • TERMINATED:终止状态

# 线程控制

// 线程休眠
Thread.sleep(1000); // 休眠1秒

// 线程加入
Thread thread = new Thread(() -> {
    // 执行任务
});
thread.start();
thread.join(); // 等待线程结束

// 线程中断
thread.interrupt();
boolean interrupted = Thread.interrupted();

# 线程同步

# synchronized关键字

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

# Lock接口

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

# 线程通信

# wait/notify机制

public class Producer {
    private final Queue<String> queue;
    private final int capacity;

    public void produce(String data) throws InterruptedException {
        synchronized (queue) {
            while (queue.size() == capacity) {
                queue.wait();
            }
            queue.add(data);
            queue.notify();
        }
    }
}

public class Consumer {
    private final Queue<String> queue;

    public String consume() throws InterruptedException {
        synchronized (queue) {
            while (queue.isEmpty()) {
                queue.wait();
            }
            String data = queue.remove();
            queue.notify