目录
问题2:原子性缺失(竞态条件 Race Condition)
Java提供了良好的多线程支持,但多线程编程不仅仅是启动多个Thread,更要正确、安全、高效地处理线程间的协作。本文总结和解决Java多线程编程的经典问题及陷阱,并通过丰富的代码实例加以说明。
1. 线程安全问题和解决方案
问题1:共享变量的可见性
陷阱说明:
被多个线程访问的变量如果没有适当同步,线程之间可能无法看到变量的最新值,导致逻辑错误。
代码演示:
Java
public class VisibilityDemo {
private static boolean running = true;
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
while (running) {
// do something
}
System.out.println("Thread stopped");
});
t.start();
Thread.sleep(1000);
running = false; // 这个修改,t线程可能“看不见”
}
}
解决方法:使用volatile关键字或同步机制。
Java
private static volatile boolean running = true; // 加volatile
或者:
Java
private static boolean running = true;
private static final Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
while (isRunning()) {
}
System.out.println("Thread stopped");
});
t.start();
Thread.sleep(1000);
setRunning(false);
}
public static synchronized boolean isRunning() {
return running;
}
public static synchronized void setRunning(boolean value) {
running = value;
}
问题2:原子性缺失(竞态条件 Race Condition)
陷阱说明:
多个线程同时对共享变量写操作时,可能发生结果错误,因为像i++其实不是原子操作。
问题代码:
Java
public class RaceConditionDemo {
private static int counter = 0;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> { for (int i = 0; i < 10000; i++) counter++; });
Thread t2 = new Thread(() -> { for (int i = 0; i < 10000; i++) counter++; });
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter); // 结果<20000
}
}
解决方法:加锁或使用原子类
(1)用synchronized关键字:
Java
private static int counter = 0;
private static final Object LOCK = new Object();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
synchronized(LOCK) {
counter++;
}
}
});
// ... 同理
}
(2)用原子类型类:
Java
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicDemo {
private static AtomicInteger counter = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {

最低0.47元/天 解锁文章

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



