Files
home/docs/java/thread.md
2026-05-13 16:24:00 +08:00

199 lines
4.0 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 多线程编程
## 线程基础
### 创建线程
#### 方式一继承Thread类
```java
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程运行中:" + Thread.currentThread().getName());
}
}
// 使用
MyThread thread = new MyThread();
thread.start();
```
#### 方式二实现Runnable接口
```java
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("线程运行中:" + Thread.currentThread().getName());
}
}
// 使用
Thread thread = new Thread(new MyRunnable());
thread.start();
// 使用Lambda表达式
Thread thread2 = new Thread(() -> {
System.out.println("Lambda线程运行中");
});
thread2.start();
```
#### 方式三实现Callable接口
```java
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
return sum;
}
}
// 使用
FutureTask<Integer> futureTask = new FutureTask<>(new MyCallable());
Thread thread = new Thread(futureTask);
thread.start();
// 获取返回值
Integer result = futureTask.get();
System.out.println("1到100的和" + result); // 5050
```
## 线程同步
### synchronized关键字
```java
public class Counter {
private int count = 0;
// 同步方法
public synchronized void increment() {
count++;
}
// 同步代码块
public void decrement() {
synchronized (this) {
count--;
}
}
public int getCount() {
return count;
}
}
```
### Lock接口
```java
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SafeCounter {
private int count = 0;
private final Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
return count;
}
}
```
## 线程通信
### wait/notify
```java
public class ProducerConsumer {
private final Object lock = new Object();
private boolean hasData = false;
public void produce() throws InterruptedException {
synchronized (lock) {
while (hasData) {
lock.wait(); // 等待消费
}
// 生产数据
hasData = true;
System.out.println("生产数据");
lock.notify(); // 通知消费者
}
}
public void consume() throws InterruptedException {
synchronized (lock) {
while (!hasData) {
lock.wait(); // 等待生产
}
// 消费数据
hasData = false;
System.out.println("消费数据");
lock.notify(); // 通知生产者
}
}
}
```
## 线程池
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// 创建固定大小线程池
ExecutorService executor = Executors.newFixedThreadPool(5);
// 提交任务
for (int i = 0; i < 10; i++) {
final int taskId = i;
executor.submit(() -> {
System.out.println("任务 " + taskId + "" +
Thread.currentThread().getName() + " 执行");
});
}
// 关闭线程池
executor.shutdown();
```
### ThreadPoolExecutor
```java
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
ThreadPoolExecutor executor = new ThreadPoolExecutor(
2, // 核心线程数
5, // 最大线程数
60L, // 空闲线程存活时间
TimeUnit.SECONDS, // 时间单位
new ArrayBlockingQueue<>(10) // 任务队列
);
executor.execute(() -> {
System.out.println("执行任务");
});
executor.shutdown();
```