2016-07-26 1 views
0

각 스레드마다 함수가 몇 번 호출되었는지 어떻게 계산할 수 있습니까?각 스레드에 대해 함수가 몇 번 호출되었는지 어떻게 계산할 수 있습니까?

같은 기능을 호출하는 많은 흐름이 있다고 가정합니다. 나는 매개 변수를 전달하기 위해 그것들을 모두 변경해야하는데, 이것은 호출 수를 유지할 것이다. 하지만 함수 서명을 수정하지 않는 대신 스레드 로컬 변수를 유지하고 얼마 동안 값을 출력하는 방법을 찾고 있습니다.

답변

1

나는 당신이 방법은 호출 된 총 횟수를 계산하려면, 정적 AtomicInteger 또는 AtomicLong를 사용할 수 있습니다

//a counter declared in your class 
private static int counter; 

... 
... 

public void someMethod foo() { 
     synchronized(counter){ 
      counter++; 
     } 


     //rest of your logic 
     ... 
    } 
} 
0

간단한 동기화 블록을 사용하여 할 수있는 것 같아요. 당신이 각 스레드에 대해 별도의 수를 유지하려면

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; 
    } 
} 
-1

바단 호배 니스 얀에게

당신은 함수 나 메소드 내부 변수를 동기화 사용해야합니다

, 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++; 
     } 
} 
관련 문제