Chr*_*lom 7 java concurrency monitoring multithreading semaphore
我试图测量有多少线程同时执行一段代码.目前我(ab)使用信号量,有更好的方法吗?
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
Run Code Online (Sandbox Code Playgroud)
使用AtomicInteger而不是a Semaphore.
有点像:
AtomicInteger count = new AtomicInteger();
count.getAndIncrement();
// do some computations
// track how many threads are running the section
trackThreads( count.get() );
count.getAndDecrement(); // end of section
Run Code Online (Sandbox Code Playgroud)