[英]Java Threads - Keep function in sync with multiple returning values from threads
This is just a concept :这只是一个概念:
How do I ensure my values never clash or my function is looking at an older value not yet updated?如何确保我的值永远不会发生冲突或我的函数正在查看尚未更新的旧值?
I'm new to threads so any information is valuable.我是线程的新手,所以任何信息都很有价值。
This a job for AtomicInteger
!这是
AtomicInteger
的工作!
AtomicInteger atomic;
...
int newValue = atomic.accumulateAndGet(rand, Math::max);
How do I ensure my values never clash?
我如何确保我的价值观永远不会发生冲突?
If you are new to threads, then I would say, use a synchronized block:如果您不熟悉线程,那么我会说,使用同步块:
final Object lock = new Object();
int global_r = 0;
...
while (true) {
int r = random.nextInt();
synchronized(lock) {
if (r > global_r) {
global_r = r;
break;
}
}
}
Only one thread at a time can enter the synchronized(lock)...
block.一次只有一个线程可以进入
synchronized(lock)...
块。 A thread that tries when another thread already is in it will be forced to wait.当另一个线程已经在其中时尝试的线程将被迫等待。
One should always try to have threads spend as little time as possible inside a synchronized(...)
block, which is why I generate the random number outside of the block, and only do the test and the assignment inside it.应该始终尝试让线程在
synchronized(...)
块内花费尽可能少的时间,这就是为什么我在块外生成随机数,并且只在其中进行测试和赋值。
Another answer here suggests that you use AtomicInteger
.这里的另一个答案建议您使用
AtomicInteger
。 That works too, but it is not what I would recommend for somebody who is taking their very first steps toward understanding how to use threads.这也有效,但对于那些正在迈出了解如何使用线程的第一步的人,我不建议这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.