【发布时间】:2016-11-10 12:40:47
【问题描述】:
我有两个线程,每个线程都有自己的计数器:线程 A 有 counterA,线程 B 有 counterB。每个线程都必须使用两个计数器:线程 A 必须使用 counterA 和 counterB,线程 B 也必须同时使用两者。 我正在使用 AtomicInteger 并在两个线程之间共享计数器,我将它们作为参数传递给线程,每个线程将两个计数器存储在私有字段中。
// ...
AtomicInteger counterA = new AtomicInteger(0);
AtomicInteger counterB = new AtomicInteger(0);
Thread tA = new Thread(new RunnableA(counterA, counterB));
Thread tB = new Thread(new RunnableB(counterA, counterB));
// ... in the constructor of RunnableA ...
RunnableA(AtomicInteger counterA, AtomicInteger counterB) {
this.counterA = counterA;
this.counterB = counterB;
}
//...
// The same for RunnableB
这是两个计数器中的safe publishing 吗? 安全发布是必要的,因为对对象的引用不够安全,无法在线程之间共享对象。 在这种情况下如何实现安全发布?
提前致谢。
【问题讨论】:
标签: java thread-safety safe-publication