文章目录
掌握多线程:深入Java并发编程
引言
在现代软件开发中,多线程编程是提高应用程序性能和响应性的关键技术。通过并行处理,我们可以充分利用多核处理器的能力,同时执行多个任务。Java作为一种广泛使用的编程语言,提供了丰富的多线程支持。本文将深入探讨Java中的多线程编程,包括基本概念、实现方式、线程同步、线程池、设计模式以及最佳实践。
多线程基础
什么是多线程?
多线程是指一个程序中可以有多个线程同时执行。线程是程序执行的最小单元,每个线程都有自己独立的执行路径和堆栈。在多线程环境中,线程可以共享程序的内存资源,但每个线程有自己的栈和局部变量。
线程的生命周期
线程的生命周期包括以下几个状态:
- 新建(New):新创建的线程尚未启动。
- 可运行(Runnable):线程准备运行,等待CPU时间。
- 运行(Running):线程正在执行。
- 阻塞(Blocked):线程等待某些条件(如I/O操作)完成。
- 等待(Waiting):线程等待另一个线程执行某个操作。
- 超时等待(Timed Waiting):线程等待另一个线程在指定时间内执行某个操作。
- 死亡(Dead):线程执行完毕或被强制终止。
Java中的多线程实现
继承Thread类
Java提供了两种主要的方式来实现多线程:继承Thread
类和实现Runnable
接口。
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread " + Thread.currentThread().getName() + " is running: " + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start();
thread2.start();
}
}
实现Runnable接口
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Runnable " + Thread.currentThread().getName() + " is running: " + i);
}
}
}
public class Main {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnable());
Thread thread2 = new Thread(new MyRunnable());
thread1.start();
thread2.start();
}
}
Callable和Future
Java 5引入了Callable
接口,它与Runnable
类似,但可以返回结果,并且可以抛出异常。
public class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
return 123;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException, ExecutionException {
FutureTask<Integer> future = new FutureTask<>(new MyCallable());
new Thread(future).start();
Integer result = future.get(); // 等待结果
System.out.println("Result: " + result);
}
}
线程同步
同步问题
当多个线程访问共享资源时,可能会出现数据不一致的问题。Java提供了同步机制来解决这一问题。
synchronized关键字
synchronized
关键字可以用来同步方法或代码块。
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
counter.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
counter.increment();
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Count: " + counter.getCount());
}
}
显式锁(Locks)
Java并发API提供了更灵活的锁机制,如ReentrantLock
。
public class Counter {
private final Lock lock = new ReentrantLock();
private int count = 0;
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
}
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
IntStream.range(0, 10).forEach(i -> {
Thread thread = new Thread(() -> {
for (int j = 0; j < 10000; j++) {
counter.increment();
}
});
thread.start();
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Count: " + counter.getCount());
}
}
线程池
为什么使用线程池?
线程的创建和销毁需要消耗系统资源。线程池可以复用线程,减少资源消耗,提高效率。
Executor框架
Java通过java.util.concurrent
包提供了强大的线程池管理功能。
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
executor.submit(() -> {
System.out.println("Task " + i + " is running on " + Thread.currentThread().getName());
});
}
executor.shutdown();
}
}
多线程设计模式
生产者-消费者模式
生产者-消费者模式是多线程编程中的经典模式,适用于处理任务队列。
public class ProducerConsumer {
private final List<Integer> list = new ArrayList<>();
private final int capacity = 10;
private final Lock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
public void produce(int num) throws InterruptedException {
lock.lock();
try {
while (list.size() == capacity) {
notFull.await();
}
list.add(num);
notEmpty.signal();
} finally {
lock.unlock();
}
}
public int consume() throws InterruptedException {
lock.lock();
try {
while (list.isEmpty()) {
notEmpty.await();
}
int num = list.remove(0);
notFull.signal();
return num;
} finally {
lock.unlock();
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
ProducerConsumer pc = new ProducerConsumer();
Thread producer = new Thread(() -> {
for (int i = 0; i < 100; i++) {
try {
pc.produce(i);
System.out.println("Produced: " + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread consumer = new Thread(() -> {
for (int i = 0; i < 100; i++) {
try {
int num = pc.consume();
System.out.println("Consumed: " + num);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
producer.start();
consumer.start();
producer.join();
consumer.join();
}
}
读者-写者模式
读者-写者模式允许多个线程同时读取共享资源,但写入时需要独占访问。
public class ReaderWriter {
private final Lock lock = new ReentrantLock();
private final Condition noReaders = lock.newCondition();
private int data = 0;
public void write(int data) {
lock.lock();
try {
while (hasReaders()) {
noReaders.await();
}
this.data = data;
System.out.println("Data written: " + data);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void read() {
lock.lock();
try {
while (hasWriters()) {
lock.await();
}
System.out.println("Data read: " + data);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
private boolean hasReaders() {
return lock.getReadHoldCount() > 0;
}
private boolean hasWriters() {
return lock.getWriteHoldCount() > 0;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
ReaderWriter rw = new ReaderWriter();
IntStream.range(0, 5).forEach(i -> {
Thread reader = new Thread(() -> {
for (int j = 0; j < 10; j++) {
try {
rw.read();
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
reader.start();
});
Thread writer = new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
rw.write(i);
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
writer.start();
writer.join();
}
}
避免死锁
死锁发生在两个或多个线程相互等待对方释放资源。设计时应注意避免死锁。
- 锁定资源的顺序一致
- 使用超时锁定
- 避免在持有锁时调用外部方法
线程安全
确保共享资源的访问是线程安全的,使用同步机制或不可变对象。
- 使用
volatile
关键字保证变量的可见性 - 使用同步代码块或方法
- 使用并发集合,如
ConcurrentHashMap
线程局部变量
使用线程局部变量(ThreadLocal
)来存储线程特定的数据。
public class ThreadLocalExample {
private static final ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
int value = threadLocal.get();
threadLocal.set(value + 1);
System.out.println("Thread " + Thread.currentThread().getName() + ", Value: " + value);
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 10; i++) {
int value = threadLocal.get();
threadLocal.set(value + 1);
System.out.println("Thread " + Thread.currentThread().getName() + ", Value: " + value);
}
});
thread1.start();
thread2.start();
}
}
结语
多线程编程是一个复杂但强大的工具,可以显著提高程序的性能和响应性。理解多线程的基本概念、掌握Java的多线程API,并遵循最佳实践,可以帮助你编写高效且可靠的并发程序。