Java 多线程使用详解
多线程是 Java 中实现并发编程的重要机制,能够充分利用多核处理器资源,提高程序的执行效率。下面我将通过实际案例和应用场景,详细介绍 Java 多线程的使用。
1. 线程创建的几种方式
1.1 继承 Thread 类
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("当前线程名称:" + Thread.currentThread().getName());
// 线程执行的任务
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
public static void main(String[] args) {
// 创建线程对象
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
// 设置线程名称
thread1.setName("线程1");
thread2.setName("线程2");
// 启动线程
thread1.start();
thread2.start();
}
}
1.2 实现 Runnable 接口(推荐)
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("当前线程名称:" + Thread.currentThread().getName());
// 线程执行的任务
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
public static void main(String[] args) {
// 创建任务对象
MyRunnable myRunnable = new MyRunnable();
// 创建线程对象,并将任务对象作为参数传入
Thread thread1 = new Thread(myRunnable, "线程1");
Thread thread2 = new Thread(myRunnable, "线程2");
// 启动线程
thread1.start();
thread2.start();
}
}
1.3 实现 Callable 接口(可获取返回值)
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ExecutionException;
public class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("当前线程名称:" + Thread.currentThread().getName());
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
return sum;
}
public static void main(String[] args) {
// 创建任务对象
MyCallable myCallable = new MyCallable();
// 使用FutureTask包装Callable对象
FutureTask<Integer> futureTask1 = new FutureTask<>(myCallable);
FutureTask<Integer> futureTask2 = new FutureTask<>(myCallable);
// 创建线程对象
Thread thread1 = new Thread(futureTask1, "线程1");
Thread thread2 = new Thread(futureTask2, "线程2");
// 启动线程
thread1.start();
thread2.start();
try {
// 获取线程执行结果
System.out.println("线程1结果:" + futureTask1.get());
System.out.println("线程2结果:" + futureTask2.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
1.4 使用 Lambda 表达式(Java 8+)
public class LambdaThread {
public static void main(String[] args) {
// 使用Lambda表达式创建Runnable实例
Thread thread1 = new Thread(() -> {
System.out.println("当前线程名称:" + Thread.currentThread().getName());
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}, "Lambda线程1");
thread1.start();
}
}
2. 线程生命周期和状态
Java 线程有以下几种状态:
- NEW(新建)
- RUNNABLE(可运行)
- BLOCKED(阻塞)
- WAITING(等待)
- TIMED_WAITING(计时等待)
- TERMINATED(终止)
3. 线程同步机制
3.1 synchronized 关键字
public class SynchronizedExample {
private int count = 0;
// 同步方法
public synchronized void increment() {
count++;
}
// 同步代码块
public void incrementBlock() {
synchronized(this) {
count++;
}
}
public static void main(String[] args) throws InterruptedException {
SynchronizedExample example = new SynchronizedExample();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
example.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
example.increment();
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("最终计数: " + example.count);
}
}
3.2 Lock 接口
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockExample {
private int count = 0;
private final Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock(); // 确保锁被释放
}
}
pub