java:监视工作线程的模式? [英] java: Patterns for Monitoring worker threads?

查看:85
本文介绍了java:监视工作线程的模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

并且原谅多线程应用程序缺乏知识,但我是该领域的新手。

and excuse the lack of knowledge on multithreaded apps, but I am new to the field.

是否有一种模式或常用的方法来监控'工作完成来自监视器(充当监视器的类)的工作线程的'或'作业状态'?

Is there a pattern or common used methodology for monitoring the 'job completion' or 'job status' of worker threads from a monitor (a class that acts as a monitor)?

我目前所做的是创建一个工人列表并为每个工人创建一个线程。在所有线程开始之后,我循环遍历工作者列表并通过调用方法来检查其状态。

What I have currently done is create a list of workers and create one thread for each worker. After all threads have started i am looping over the worker list and 'checking their status' by making a call to a method.

那时我无法上来我有一个不同的解决方案,但对于该领域的新手,我不知道这是否可行,或者我是否应该研究其他解决方案或模式。

At that time I couldn't come up with a different solution, but being new to the field, I don't know if this is the way to go, or if there are other solutions or patterns that I should study.

推荐答案

根据您的需要,有很多方法可以做到这一点。

Depending on what you want, there are many ways that you can do this.

如果你只是想等直到所有线程完成(即你所关心的所有内容都在完成之前完成所有内容),你可以使用 Thread.join()

If you just want to wait until all the threads finish (i.e. all you care about is having everything finish before moving on), you can use Thread.join():

try {
    for (Thread t: threadsIWaitOn)
        t.join();
} catch (InterruptedException iex) {
     /* ... handle error ... 
}

如果你想对线程状态进行更精细的控制,并希望能够随时知道线程在做什么,你可以使用线程.getState()函数。这将返回一个 Thread.State 对象,该对象描述该线程是否正在运行,阻塞,是否等等,而Javadoc特别声明它是专为监视线程状态而设计的而不是试图同步它。这可能是你想要做的。

If you want a more fine-grained control over the thread status and want to be able, at any time, to know what threads are doing, you can use the Thread.getState() function. This returns a Thread.State object that describes whether the thread is running, blocked, new, etc., and the Javadoc specifically says that it's designed for monitoring the state of a thread rather than trying to synchronize on it. This might be want you want to do.

如果你想要更多的信息 - 比如,如何获得从0到0的每个线程的进度指示器线程进展100 - 然后另一个选项可能是从线程创建 Map AtomicInteger 将每个线程与计数器相关联,然后将 AtomicInteger 传递给每个线程的构造函数。这样,每个线程可以连续递增计数器,你可以有另一个线程连续轮询进度。

If you want even more information than that - say, how to get a progress indicator for each thread that counts up from 0 to 100 as the thread progresses - then another option might be to create a Map from Threads to AtomicIntegers associating each thread with a counter, then pass the AtomicInteger into the constructor of each thread. That way, each thread can continuously increment the counters, and you can have another thread that continuously polls the progress.

简而言之,你有很多选择基于什么这是你想要完成的。希望这里的东西有所帮助!

In short, you have a lot of options based on what it is that you're trying to accomplish. Hopefully something in here helps out!

这篇关于java:监视工作线程的模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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