【发布时间】:2020-04-04 17:44:54
【问题描述】:
我正在尝试在多线程环境中使用 AtomicLong。我想要的结果不起作用,
public class Account implements Runnable {
private final AtomicLong amount = new AtomicLong(0);
public Account(long difference) {
amount.set(difference);
}
public void run() {
System.out.println("The Balance is : " + amount);
}
}
public class Examples {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(10);
IntStream.range(0, 100).forEach(i -> service.submit(new Account(i)));
}
}
我尝试使用读/写锁和块级同步,但没有成功。请问有人发现哪里出错了吗?
I 输出必须从 0,1,2...99 开始。
【问题讨论】:
-
您希望它们按顺序打印吗?在单个线程中执行它们(或使用 common 计数器并正确同步访问)。
-
谢谢汤姆。让我尝试共享数据并使其在多线程中工作。
-
我会注意到,如果您使用单个条件(内部锁的锁),如果您有大量活动线程,性能将会很差,因为它会唤醒所有线程数字 - O(n^2)。
-
是的,我同意使用内在锁的性能。
-
另外,如果你最终得到大量线程,那么你需要重新考虑代码。同步是您的最后一个问题
标签: java multithreading java.util.concurrent