简体   繁体   English

AtomicInteger与同步块

[英]AtomicInteger vs synchronized block

I have a problem where I need to synchronize access to array of integers in java. 我有一个问题,我需要同步对Java中整数数组的访问。 My code looks something like this. 我的代码看起来像这样。

   Class X {

         int[] counters = new int[100];

         Object lock = new Object ();

         void increment (int idx){
         synchronized (lock){
              ++counters[idx];
             }
          }

          void print(){ 
             StringBuffer buf = new StringBuffer ();
             synchronized (lock){
                   for( int i=0; i<100; i++;){
                     buf.append(",");
            buf.append(counters [i]);
                     } //End for
              }//End synchronized    
           System.out.println(buf.toString());
            } 
    }

Currently I am using single lock to synchronize access to array of integers. 目前,我正在使用单锁来同步对整数数组的访问。 But I want to use one lock for each counter. 但是我想为每个计数器使用一个锁。

So I modified code to something like below. 所以我将代码修改为如下所示。

    Class X {

     int[] counters = new int[100];

     Object[] locks = new Object[100];

     static{
          for(int i=0;i<100;i++){
               locks [i] = new Object ();
           }
       }

     void increment (int idx){
            synchronized (locks[idx]){
                ++counters[idx];
             }
       }

     void print(){ 
         StringBuffer buf = new StringBuffer ();
        for( int i=0; i<100; i++;){
                 buf.append(","); 
           synchronized (lock[i]){
                 buf.append(counters [i]);
            }//End synchronized
        } //End for
      System.out.println(buf.toString());
    } 
}

But my colleague suggested me to use AtomicInteger instead of synchronized blocks. 但是我的同事建议我使用AtomicInteger而不是同步块。

Does AtomicInteger has same effect as synchronized block? AtomicInteger是否具有与同步块相同的作用?

Generally, AtomicInteger has not the same effect as synchronized block. 通常,AtomicInteger与同步块的效果不同。 But for simple tasks as yours, AtomicInteger can be used to get rid of synchronized blocks: 但是对于像您这样的简单任务,可以使用AtomicInteger摆脱同步块:

AtomicInteger[] counters = new AtomicInteger[100];

void increment (int idx){
    counters[idx].incrementAndGet();
}

void print(){ 
    StringBuffer buf = new StringBuffer ();
    for( int i=0; i<100; i++;){
         buf.append(","); 
         buf.append(counters[i].get);
    } //End for
    System.out.println(buf.toString());
} 

You need not any synchronization for print() . 您不需要对print()任何同步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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