4.0 KiB
4.0 KiB
多线程编程
线程基础
创建线程
方式一:继承Thread类
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程运行中:" + Thread.currentThread().getName());
}
}
// 使用
MyThread thread = new MyThread();
thread.start();
方式二:实现Runnable接口
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接口
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关键字
public class Counter {
private int count = 0;
// 同步方法
public synchronized void increment() {
count++;
}
// 同步代码块
public void decrement() {
synchronized (this) {
count--;
}
}
public int getCount() {
return count;
}
}
Lock接口
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
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(); // 通知生产者
}
}
}
线程池
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
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();