Java 多线程 : Unexpected result

标签 java multithreading

我正在开发企业应用程序。在多线程环境中运行应用程序时,我遇到了一些问题。我正在编写一个程序,其中有一个变量的值正在以非常快的速度(例如每秒 10000 次更新)更新(递增)。循环运行一定的迭代,变量的值递增并存储在 HashMap 中。一旦循环终止并打印 HashMap 中的变量值。我得到了意外的变量值。

这是演示程序(请阅读评论以便更好地理解):

class test implements Runnable {

    static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
    static AtomicInteger value_to_be_incremented_stored = new AtomicInteger(0); // variable whose value to be updated
    static AtomicInteger i = new AtomicInteger(0);  // this runs the loop

    @Override
    public void run() {

        for (i.set(0); i.get() < 100000; i.incrementAndGet()) {
            /*
                This loop should run 100000 times and when loop terminates according to me value of variable 
                "value_to_be_incremented_stored" should be 100000 as its value is incremented 
                100000 times the loop also runs 100000 times. 
            */
            System.out.println("Thread > " + Thread.currentThread() + "  " + value_to_be_incremented_stored.incrementAndGet());
            map.put("TC", value_to_be_incremented_stored.intValue());
        }

        System.out.println("Output by Thread  " + Thread.currentThread() + "     " + map.toString());
    }

    public static void main(String[] args) {

        test t1 = new test();
        Thread thread1 = new Thread(t1);
        thread1.setName("Thread 1");

        Thread thread2 = new Thread(t1);
        thread2.setName("Thread 2");

        Thread thread3 = new Thread(t1);
        thread3.setName("Thread 3");

        Thread thread4 = new Thread(t1);
        thread4.setName("Thread 4");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }
}

输出(不同):

My output

问题: 我正在运行 100000 次循环 (i.get() < 100000)那么变量value_to_be_incremented_stored的值是怎么来的呢?变得超过 100000。

最佳答案

我发现了三个缺陷。一个是在比较循环计数器的点和递增它的点之间的 for 循环中存在竞争条件。您应该一步完成此操作以获得原子操作:

for ( ; i.incrementAndGet() < 100000;  ) {

另一个是在你的计数器的增量和将它放置在 map 中之间也存在竞争条件。即使您按顺序递增它们,任何线程在内部都可能具有不同的值(它在循环中的不同点)并且它可以将先前的值放入全局映射中。您需要此处的原子性以确保您增加的值是您放置在循环中的值。

synchronized( lock ) { 
    value_to_be_incremented_stored.incrementAndGet();
    map.put("TC", value_to_be_incremented_stored.intValue());
}

最后由于某种原因 <比较为我产生了 99999 的值(value)。我不得不使用 <=修复它。

(正如我们在评论中讨论的那样,在每个 i.set(0) 循环的开头设置 for 出于相当明显的原因是行不通的。我猜有四个缺陷。)

class ThreadTestX implements Runnable {

    static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
    static AtomicInteger value_to_be_incremented_stored = new AtomicInteger(0); // variable whose value to be updated
    static AtomicInteger i = new AtomicInteger(0);  // this runs the loop
    static final Object lock = new Object();

    @Override
    public void run() {

        for ( ; i.incrementAndGet() <= 100000;  ) {
            /*
                This loop should run 100000 times and when loop terminates according to me value of variable 
                "value_to_be_incremented_stored" should be 100000 as its value is incremented 
                100000 times the loop also runs 100000 times. 
            */
            synchronized( lock ) {
                value_to_be_incremented_stored.incrementAndGet();
    //            System.out.println("Thread > " + Thread.currentThread() + 
    //                 "  " + value_to_be_incremented_stored.get());
                map.put("TC", value_to_be_incremented_stored.intValue());
            }
        }

        System.out.println("Output by Thread  " + Thread.currentThread() 
                + "     " + map.toString());
    }

    public static void main(String[] args) {

        ThreadTestX t1 = new ThreadTestX();
        Thread thread1 = new Thread(t1);
        thread1.setName("Thread 1");

        Thread thread2 = new Thread(t1);
        thread2.setName("Thread 2");

        Thread thread3 = new Thread(t1);
        thread3.setName("Thread 3");

        Thread thread4 = new Thread(t1);
        thread4.setName("Thread 4");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }
}

输出:

run:
Output by Thread  Thread[Thread 4,5,main]     {TC=100000}
Output by Thread  Thread[Thread 3,5,main]     {TC=100000}
Output by Thread  Thread[Thread 1,5,main]     {TC=100000}
Output by Thread  Thread[Thread 2,5,main]     {TC=100000}
BUILD SUCCESSFUL (total time: 0 seconds)

事后思考:尽管被标记为正确,但我不确定自己是否正确。这里的问题是您试图使三件事保持同步:循环计数器 i ,要递增的值,以及 map 。允许其中任何一个在同步块(synchronized block)之外执行可能会使它们处于意外状态。我认为以下可能更安全:

@Override
public void run() {

    for ( ;;  ) {
        synchronized( lock ) {
            if( i.incrementAndGet() <= 100000 ) {
                value_to_be_incremented_stored.incrementAndGet();
                map.put("TC", value_to_be_incremented_stored.intValue());
            }
            else
                break;
        }
    }
    System.out.println("Output by Thread  " + Thread.currentThread() 
            + "     " + map.toString());
}

这消除了将变量声明为 AtomicInteger 的需要,但我看不出还有什么方法可以确保它们的值在该循环执行时不会改变(由于其他线程)。

关于Java 多线程 : Unexpected result,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44347670/

相关文章:

java - 自定义过滤器扩展 UrlRewriteFilter 以从数据库加载规则

java - Hibernate获取同一个对象到不同的对象

java - 其余 Jersey json 编码

java - 跳过代码导致程序提前结束

java - 线程停放在 java.util.concurrent.ThreadPoolExecutor.getTask 的原因可能是什么

java - 如何将日志记录与异常处理链结合起来?

java - 如何停止 Java Android 中的线程?

c - 信号处理程序是否需要包含在流程中的每个可能上下文中?

Java 执行器 : wait for task termination.

java - 线程上下文类加载器可以为空吗?