我如何衡量有多少线程正在执行一段代码? [英] How can I measure how many threads are executing a piece of code?

查看:79
本文介绍了我如何衡量有多少线程正在执行一段代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测量有多少线程正在同时执行一段代码. 目前,我正在使用信号量,是否有更好的方法?

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

推荐答案

使用类似于:

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

这篇关于我如何衡量有多少线程正在执行一段代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆