线程安全
挑战:多个线程同时访问共享资源时,可能导致数据不一致或状态错误。
应对策略:
使用同步机制(如 synchronized 关键字、ReentrantLock 等)来保护共享资源。
使用无锁数据结构(如 ConcurrentHashMap、CopyOnWriteArrayList 等)来减少锁的竞争。
在多线程编程中,线程安全问题通常出现在多个线程同时访问或修改共享资源时,可能导致数据不一致或状态错误。为了避免这些问题,我们可以使用同步机制或无锁数据结构。下面是几种常见的线程安全应对策略及其使用场景和代码示例。
1. 使用 synchronized
关键字
synchronized
是 Java 中的一种同步机制,它能够确保同一时刻只有一个线程可以访问某个方法或代码块。
场景:
当多个线程需要访问同一个方法,并且该方法修改了共享资源时,使用 synchronized
可以避免数据竞争。
代码示例:
public class ThreadSafeExample {
private int counter = 0;
// 使用 synchronized 保证线程安全
public synchronized void increment() {
counter++;
}
public synchronized int getCounter() {
return counter;
}
public static void main(String[] args) throws InterruptedException {
ThreadSafeExample example = new ThreadSafeExample();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Counter value: " + example.getCounter());
}
}
在这个示例中,increment
方法被 synchronized
修饰,确保了每次只有一个线程能修改 counter
变量。
2. 使用 ReentrantLock
ReentrantLock
提供了比 synchronized
更灵活的锁机制。它允许手动控制锁的获取和释放,提供了超时机制和尝试锁等功能。
场景:
当你需要更精细的控制锁的行为时(如尝试获取锁、超时机制等),使用 ReentrantLock
会更合适。
代码示例:
import java.util.concurrent.locks.ReentrantLock;
public class ThreadSafeExample {
private int counter = 0;
private final ReentrantLock lock = new ReentrantLock();
public void increment() {
lock.lock(); // 手动获取锁
try {
counter++;
} finally {
lock.unlock(); // 确保锁最终会被释放
}
}
public int getCounter() {
return counter;
}
public static void main(String[] args) throws InterruptedException {
ThreadSafeExample example = new ThreadSafeExample();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Counter value: " + example.getCounter());
}
}
在这个示例中,ReentrantLock
被用来保护共享资源 counter
,确保线程安全。
3. 使用无锁数据结构(如 ConcurrentHashMap
)
无锁数据结构(如 ConcurrentHashMap
)允许多个线程并发访问数据,而不会引起线程安全问题,适用于读多写少的场景。
场景:
当你需要高并发访问数据并且数据修改较少时,使用 ConcurrentHashMap
等无锁数据结构能够避免性能瓶颈。
代码示例:
import java.util.concurrent.ConcurrentHashMap;
public class ThreadSafeExample {
private ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
public void increment(String key) {
map.merge(key, 1, Integer::sum);
}
public int getValue(String key) {
return map.getOrDefault(key, 0);
}
public static void main(String[] args) throws InterruptedException {
ThreadSafeExample example = new ThreadSafeExample();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.increment("key1");
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.increment("key1");
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Value for 'key1': " + example.getValue("key1"));
}
}
在这个示例中,ConcurrentHashMap
允许在多个线程之间安全地并发操作 map
,避免了使用传统的同步机制所带来的性能损失。
总结:
- 使用
synchronized
:当你只需要保护一小段代码,且对性能要求不高时,使用synchronized
最简单。 - 使用
ReentrantLock
:当你需要更多的锁控制,如超时、尝试锁等功能时,使用ReentrantLock
。 - 使用无锁数据结构:如
ConcurrentHashMap
,适合高并发的场景,减少了锁的竞争。