本文介绍了计算多线程环境中类的实例数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在尝试计算在多线程环境下进程运行时生成的类的实例数量.我的方法是通过查看这篇文章在构造函数中增加一个静态计数器:如何计算类的实例数

I am trying to count how many instances of a class generated during the run time of a process under multi-threading environment. The way how I do it is to increase a static counter in the constructor by looking at this post:How to Count Number of Instances of a Class

所以在多线程环境中,我是这样定义类的:

So in multi-threading environment, here is how i define the class:

class Television {
      private static volatile int counter = 0;
      public Television(){
             counter ++;
      }
}

但是,我不确定上面的代码是否存在潜在的错误,因为我认为 java 中的构造函数并不意味着同步counter++ 不是atomic 所以如果两个线程同时创建实例,代码是否是一个错误?但我还不太确定.

However, I am not sure whether there is a potential bug with the code above since I think constructor in java does not imply synchronization and counter++ is not atomic so if two threads are creating instances simultaneously, is the code a bug somehow? but I am not quite sure yet.

推荐答案

这段代码中存在一个错误(特别是竞争条件),因为计数器的读取和计数器的写入不是以原子方式执行的.

There is a bug in this code (specifically, a race condition), because the read of counter and write to counter aren't atomically executed.

换句话说,两个线程可以读取 counter 的相同值,增加该值,然后将相同的值写回变量.

In other words, two threads can read the same value of counter, increment that value, and then write the same value back to the variable.

Thread 1    Thread 2
========    ========

Read 0
            Read 0
Increment
            Increment
Write 1
            Write 1

所以之后的值将是 1,而不是 2.

So the value would be 1, not 2, afterwards.

使用 AtomicIntegerAtomicInteger.incrementAndGet() 代替.

这篇关于计算多线程环境中类的实例数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 11:52