简体   繁体   English

Java 线程 - 使函数与线程的多个返回值保持同步

[英]Java Threads - Keep function in sync with multiple returning values from threads

This is just a concept :这只是一个概念:

  • I want to have a int be updated, by a function that is running inside multiple threads.我想通过在多个线程内运行的函数来更新 int 。
  • My function randomly chooses an int and checks if it's bigger than the existing int.我的函数随机选择一个 int 并检查它是否大于现有的 int。
  • If so it updates the variable.如果是这样,它会更新变量。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM