
本文详解为何原始多线程实现无法更新共享数组,并提供线程安全、无竞态、可复用的解决方案,涵盖参数传递、Runnable 替代继承 Thread、线程同步等待等核心要点。
本文详解为何原始多线程实现无法更新共享数组,并提供线程安全、无竞态、可复用的解决方案,涵盖参数传递、`runnable` 替代继承 `thread`、线程同步等待等核心要点。
在 Java 中,试图通过多线程并行计算(如 LeetCode 238 题 Product of Array Except Self)提升性能时,一个常见误区是错误地依赖静态字段共享数据。原始代码中将 nums 和 answer 声明为 public static,看似能被所有线程访问,实则引发两大根本性问题:
- 静态字段污染与线程不安全:static 字段属于类而非实例,多个 Solution 实例(尤其在 OJ 环境中反复调用)会相互覆盖 nums 和 answer,导致不可预测的读写结果;
- 构造逻辑缺陷:Threaded 继承 Thread 但未正确传递 nums 和 answer 引用——其构造器仅接收 i 和 ThreadGroup,而 run() 中直接访问 Solution 的静态字段,造成“看似传参、实则空悬”的假象。
✅ 正确做法是:彻底摒弃静态共享,改用实例字段 + 显式参数注入。重构后的方案如下:
- Threaded 改为实现 Runnable 接口(更符合组合优于继承原则);
- 构造器显式接收 nums、answer 和索引 i,确保每个线程拥有独立、明确的数据视图;
- 主线程使用 ThreadGroup.activeCount() 轮询等待虽可用,但更推荐 Thread.join()(见下方优化建议)。
class Solution {
public int[] productExceptSelf(int[] nums) {
int[] answer = new int[nums.length];
Thread[] threads = new Thread[nums.length];
// 启动每个线程,传入所需数据副本
for (int i = 0; i < nums.length; i++) {
threads[i] = new Thread(new Threaded(nums, answer, i), "Worker-" + i);
threads[i].start();
}
// ✅ 推荐替代方案:用 join() 替代 activeCount() 轮询(更可靠、更易读)
try {
for (Thread t : threads) t.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Thread interrupted", e);
}
return answer;
}
}
class Threaded implements Runnable {
private final int[] nums; // final 保证不可变引用,增强线程安全性
private final int[] answer;
private final int i;
Threaded(int[] nums, int[] answer, int i) {
this.nums = nums;
this.answer = answer;
this.i = i;
}
@Override
public void run() {
answer[i] = computeProduct(nums, i);
}
private int computeProduct(int[] nums, int excludeIndex) {
int product = 1;
for (int j = 0; j < nums.length; j++) {
if (j != excludeIndex) {
product *= nums[j];
}
}
return product;
}
}⚠️ 关键注意事项:
- 避免 static 共享状态:OJ 环境中 Solution 实例可能被复用或并发调用,静态字段会成为全局污染源;
- join() 优于 activeCount():后者存在竞态(如线程刚结束但计数未刷新),且轮询消耗 CPU;join() 是阻塞式、精确的等待机制;
- final 字段提升安全性:防止意外重赋值,明确表达“只读输入”语义;
- 性能提醒:本题多线程实际不会提速——数组遍历本身是内存带宽受限操作,线程创建/调度开销远超计算收益。真正的最优解是 O(1) 空间、两次遍历的单线程算法(左积 × 右积)。多线程在此场景属过度工程。
综上,线程安全的本质不是“让变量可见”,而是“控制谁在何时以何种方式访问它”。通过显式参数传递、消除静态依赖、采用标准同步原语,才能写出健壮、可维护的并发代码。
立即学习“Java免费学习笔记(深入)”;


















