【问题标题】:Tracking the spawned threads in ThreadPoolExecutor java在 ThreadPoolExecutor java 中跟踪生成的线程
【发布时间】:2016-03-02 03:48:42
【问题描述】:

我正在使用线程池生成 5 个线程。现在我想知道跟踪所有这些线程并捕获每个线程的指标的最佳方法,例如

  • 每个线程花费了多少时间?
  • 每个线程使用了多少内存?

我们是否有任何现成的实现可以为我们完成这项工作。任何建议都会有所帮助。

public static void main(String[] args) {

        ThreadPoolExecutor executors = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);

        System.out.println("at executors step");
        List<String> getlist = getList();
        for (Iterator<String> itr = getlist.iterator(); itr.hasNext();) {
            String element = (String) itr.next();
            String[] command = { "ssh", "hddev-c01-edge-02", "\"" + element + "\"" };
            System.out.println("the command is as below ");
            System.out.println(Arrays.toString(command));
            System.out.println("inside the iterator");
            ParallelExecutor pe = new ParallelExecutor(command);
            executors.execute(pe);
        }
        executors.shutdown();
    }

【问题讨论】:

  • 内存将难以测量,因为堆内存在所有线程之间共享并由垃圾收集器在后台管理。
  • 如果没有内存,是否可以跟踪线程?
  • 当 foreach 循环既简单又清晰时,为什么要使用Iterator?附言另外,使用 Java SSH 库而不是运行随机的外部进程。
  • 回答您的问题:使用分析器。例如 JDK 附带的 VisualVM
  • 嗨,鲍里斯,正如您正确指出的那样。我同意你使用 foreach 循环会更简单,但我通常使用 Iterator 所以有点偏颇:)

标签: java multithreading threadpoolexecutor


【解决方案1】:

在 ThreadPoolExecutor 中有 2 种方法,您可以重写它们来做这种内务管理,例如线程执行 Runnable 所花费的时间。 扩展 ThreadPoolExecutor 并仅覆盖 2 个方法,例如,

protected void beforeExecute(Thread t, Runnable r) { }

protected void afterExecute(Runnable r, Throwable t) { }

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 2015-08-22
    相关资源
    最近更新 更多