我正在尝试测量有多少线程同时执行一段代码。目前我正在(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
发布于 2017-12-13 14:30:49
使用AtomicInteger而不是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
发布于 2017-12-13 20:21:28
AtomicInteger
是一个很好的建议,但是由于java-8已经有了LongAdder
,它更适合竞争激烈的环境。
不同之处在于,当CAS
失败时,AtomicInteger
会再次尝试,直到成功为止。当LongAdder
失败时(里面有一个自旋锁),它将创建一个“失败”的值的数组(如果我没记错的话,限制在CPU的数量)。当你最终请求它的当前值时-所有那些“失败”的值都会被添加到结果中。事实证明,这种策略比AtomicInteger
快得多。
https://stackoverflow.com/questions/47795282
复制