java线程不安全代码示例
时间: 2023-06-20 20:06:02 浏览: 74
以下是一个简单的Java线程不安全的示例代码:
```java
public class UnsafeThread {
private int count = 0;
public void increment() {
count++;
}
public int getCount() {
return count;
}
public static void main(String[] args) throws InterruptedException {
UnsafeThread unsafeThread = new UnsafeThread();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
unsafeThread.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
unsafeThread.increment();
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("Count: " + unsafeThread.getCount());
}
}
```
该示例代码中有一个共享变量 `count`,两个线程会并发地对这个变量进行累加操作。由于 `count++` 操作不是原子性的,会分为读取变量、加1、写入变量三个步骤,因此在并发执行时,可能会出现竞态条件导致结果不正确。
例如,当 `count` 的值为9999时,线程1和线程2都执行了 `count++` 操作,但由于没有互斥机制,两个线程都读取了 `count` 的值为9999,然后各自加1并写回到 `count` 中,结果 `count` 的值只增加了1,变成了10000,而不是预期的20000。
要解决线程不安全的问题,可以使用同步机制,例如使用 `synchronized` 关键字或者使用 `java.util.concurrent.atomic` 中提供的原子类。