多线程应用程序中的静态计数器线程是否安全? [英] Is a static counter thread safe in multithreaded application?

查看:86
本文介绍了多线程应用程序中的静态计数器线程是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class counting
{
  private static int counter = 0;

  public void boolean counterCheck(){
  counter++;
  if(counter==10)
  counter=0;
  }
}

我的应用程序中的多个线程可以访问方法counterCheck 。我知道静态变量不是线程安全的。如果有人可以帮助我举例,或者告诉我为什么我必须同步方法或阻止,我将不胜感激。如果我不同步会发生什么?

Method counterCheck can be accessed by multiple threads in my application. I know that static variables are not thread safe. I would appreciate if someone can help me with example or give me reason why I have to synchronize method or block. What will happen if I don't synchronize?

推荐答案

这不是线程安全的, AND 这个从多个线程更新计数的模式可能是实现多线程应用程序的负扩展(当你添加更多线程时运行速度较慢)的第一种方式。

This is not thread safe, AND this pattern of updating a count from multiple threads is probably the #1 way to achieve negative scaling (it runs slower when you add more threads) of a multi-threaded application.

如果你添加必要的锁定以使这个线程安全,那么每个线程将在计数时完全停止。即使您使用原子操作来更新计数器,您最终也会在更新计数器的每个线程之间弹跳CPU缓存行。

If you add the necessary locking to make this thread safe then every thread will come to a complete halt while counting. Even if you use atomic operations to update the counter, you will end up bouncing the CPU cache line between every thread that updates the counter.

现在,这不是问题如果每个线程操作在更新计数器之前需要相当长的时间。但是如果每个操作都很快,计数器更新将序列化操作,导致所有线程上的一切都变慢。

Now, this is not a problem if each thread operation takes a considerable amount of time before updating the counter. But if each operation is quick, the counter updates will serialize the operations, causing everything to slow down on all the threads.

这篇关于多线程应用程序中的静态计数器线程是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆