【问题标题】:How can I calculate how many times function has been called for each thread? [closed]如何计算每个线程调用了多少次函数? [关闭]
【发布时间】:2016-07-26 09:01:20
【问题描述】:

如何计算每个线程调用了多少次函数?

所以假设有很多流,它们都在调用同一个函数。我必须全部更改它们才能传递一些参数,这将保持调用次数。但我正在寻找不修改函数签名的方法,而是保留线程局部变量并从某个时间打印其值。

【问题讨论】:

    标签: java thread-local java-threads


    【解决方案1】:

    我猜你可以使用简单的同步块来做到这一点

    //a counter declared in your class
    private static int counter;
    
    ...
    ...
    
    public void someMethod foo() {  
            synchronized(counter){  
                counter++;  
            }  
    
    
            //rest of your logic
            ...
        }  
    }
    

    【讨论】:

      【解决方案2】:

      如果要计算方法被调用的总次数,可以使用静态 AtomicInteger 或 AtomicLong。

      class C {
          private static final AtomicInteger count = new AtomicInteger();
          public void m() {
              count.getAndIncrement();
              //... the rest of the method
          }
          public static void getCount() {
              return count.get();
          }
      }
      

      如果你想为每个线程保留一个单独的计数,你需要一个计数器映射

      class C {
          private static final ConcurrentHashMap<Long, AtomicInteger> counts = new ConcurrentHashMap<>();
          void m() {
              counts.putIfAbsent(Thread.currentThread().getId(), new AtomicInteger(0));
              counts.get(Thread.currentThread().getId()).getAndIncrement();
              //... the rest of the method
          }
      
          public static Map<Long, AtomicInteger> getCount() {
              return counts;
          }
      }
      

      【讨论】:

        【解决方案3】:

        Vardan Hovhannisyan

        你必须在函数或方法中使用同步变量,sycrhonize 是必要的,以确保在执行和计数过程中线程之间不要崩溃,以获得正确的值。

        public class exemplesyn {
              //Count variable
              private Integer countsychronized =0;
        
              //Methode to count execution
              public void executedmethodeToCount(){
                   this.countSychronized();
                   //Code to execute
              }
        
              //Synchroniced methode to count
              public synchronized void countSychronized (){
                 this.countsychronized++;
              }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-18
          • 1970-01-01
          • 1970-01-01
          • 2022-11-19
          相关资源
          最近更新 更多