You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么这段ThreadUnsafe类的Go方法不具备线程安全性?

Why the Go() method in ThreadUnsafe is Thread-Unsafe

Let’s walk through exactly why this method isn’t safe when multiple threads call it at the same time—there are two critical issues that lead to unpredictable, broken behavior:

1. Race Condition Leading to Division by Zero

The Go() method uses a check-then-act pattern that isn’t atomic. Here’s a step-by-step example of how things can go wrong:

  • Thread 1 enters Go() and checks if (val2 != 0) — let’s say val2 is 5 here, so it passes the check.
  • Before Thread 1 can execute System.out.println(val1 / val2), the operating system pauses Thread 1 and switches to Thread 2.
  • Thread 2 runs the full Go() method: it checks val2 !=0 (still 5), prints the division result, then sets val2 = 0.
  • Thread 1 resumes execution. It already passed the if check, so it tries to compute val1 / val2 — but val2 is now 0, triggering an ArithmeticException (division by zero).

This happens because the check and the subsequent division/assignment aren’t treated as a single, indivisible operation. Multiple threads can interfere with each other between these steps.

2. Visibility Issues with Unsynced Static Variables

The val1 and val2 fields are plain static variables with no synchronization or volatile modifier. In a multi-threaded environment:

  • When one thread updates val2, there’s no guarantee that other threads will see this updated value immediately. Threads might cache old values of these variables in their local memory, leading to stale reads.
  • For example, Thread A sets val2 = 0, but Thread B might still read val2 as its old non-zero value, leading it to attempt the division even though val2 was already reset.

To fix this, you’d need to wrap the entire logic in a synchronized block (or use other thread-safe constructs like AtomicInteger for the variables) to ensure atomicity and visibility.

内容的提问来源于stack exchange,提问作者JohnBanter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:29:47