How can I measure how many threads are executing a piece of code?
问题 I am trying to measure how many threads are executing a section of code at the same time. Currently i am (ab)using Semaphores for this, is there a better way? final int MAX_THREADS = Integer.MAX_VALUE; Semaphore s = new Semaphore(MAX_THREADS); s.acquire(); // start of section // do some computations // track how many threads are running the section trackThreads( (MAX_THREADS - s.availablePermits()) ); s.release(); // end of section 回答1: Use an AtomicInteger instead of a Semaphore . Something