Java 学习系列(5):Java 多线程编程详解
1. 什么是多线程?
在计算机程序运行时,通常有多个任务需要同时执行,例如:
- 服务器同时处理多个用户请求。
- 网页浏览器同时下载多个资源(HTML、CSS、JavaScript)。
- 视频播放器同时解码和播放音频、视频。
多线程(Multithreading) 是 Java 语言支持的并发编程方式,允许一个进程内部并行执行多个任务。
2. Java 线程的创建方式
在 Java 中,创建线程的方式主要有三种:
2.1 继承 Thread 类
class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程运行中: " + Thread.currentThread().getName());
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}
注意: 不能直接调用 run(),而是要使用 start() 来启动新线程。
2.2 实现 Runnable 接口
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("线程运行中: " + Thread.currentThread().getName());
}
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
区别: Runnable 方式更加灵活,避免 Java 单继承的限制。
2.3 使用 Callable 和 Future
如果需要在线程执行后返回结果,可以使用 Callable 接口。
import java.util.concurrent.*;
class MyCallable implements Callable<String> {
@Override
public String call() {
return "线程执行结果: " + Thread.currentThread().getName();
}
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new MyCallable());
System.out.println(future.get()); // 获取线程返回值
executor.shutdown();
}
}
3. 线程同步与线程安全
3.1 synchronized 关键字
多个线程访问共享资源时,可能会引发数据不一致问题。可以使用 synchronized 关键字保证线程安全。
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class SynchronizedExample {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(counter::increment);
Thread t2 = new Thread(counter::increment);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("最终计数: " + counter.getCount());
}
}
3.2 ReentrantLock
ReentrantLock 提供更灵活的锁机制。
import java.util.concurrent.locks.*;
class Counter {
private int count = 0;
private final ReentrantLock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
return count;
}
}
4. 线程池的使用
线程池用于管理多个线程,提高性能,避免频繁创建和销毁线程的开销。
import java.util.concurrent.*;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 0; i < 5; i++) {
executor.execute(() -> System.out.println(Thread.currentThread().getName() + " 执行任务"));
}
executor.shutdown();
}
}
5. volatile 关键字
volatile 关键字用于保证变量的可见性,避免线程缓存导致的数据不一致问题。
class VolatileExample {
private volatile boolean running = true;
public void stop() {
running = false;
}
}
6. ThreadLocal 变量
ThreadLocal 用于在每个线程中存储独立变量,避免共享变量的线程安全问题。
public class ThreadLocalExample {
private static final ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
public static void main(String[] args) {
new Thread(() -> {
threadLocal.set(100);
System.out.println(Thread.currentThread().getName() + " - " + threadLocal.get());
}).start();
}
}
7. Java 并发工具类
Java 提供了一些并发工具类,如 CountDownLatch、CyclicBarrier、Semaphore、ConcurrentHashMap。
7.1 CountDownLatch
import java.util.concurrent.*;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(3);
for (int i = 0; i < 3; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " 完成任务");
latch.countDown();
}).start();
}
latch.await();
System.out.println("所有任务完成");
}
}
8. 总结
- Java 线程可以通过
Thread、Runnable、Callable创建。 - 线程同步可以使用
synchronized、ReentrantLock。 volatile保证可见性,ThreadLocal提供线程独立变量。- 线程池 (
ExecutorService) 提高并发性能。 - 并发工具类 (
CountDownLatch、Semaphore) 提供更高级的线程管理。
下一期:《Java 学习系列(6):Java I/O 详解》

被折叠的 条评论
为什么被折叠?



