Java多线程同步问题:竞态条件示例
在Java多线程编程中,竞态条件是指两个或更多的线程对同一资源进行操作,由于它们的执行顺序不确定,从而导致结果不一致的问题。
下面是一个简单的竞态条件示例:
class Counter {
int count = 0;
synchronized void increment() {
count++;
notifyAll(); // 通知所有等待的线程
}
synchronized void decrement() {
count--;
if (count == 0) { // 如果计数为0,说明资源可用
notifyAll();
}
}
}
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
counter.increment(); // 执行增操作
try {
// 线程休眠一段时间,模拟资源的可用性
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}));
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 5; i++) {
counter.decrement(); // 执行减操作
try {
// 线程休眠一段时间,模拟资源的不可用性
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}));
thread1.start();
thread2.start();
try {
// 主线程等待两个子线程执行完毕
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final count: " + counter.count);
}
}
在这个示例中,Counter
类的两个方法increment()
和decrement()
分别模拟了资源的增操作和减操作。由于线程的执行顺序不确定,可能会出现先执行减操作导致结果不正确的问题。
还没有评论,来说两句吧...