首页 \ 问答 \ Java使用另一个线程检查线程的状态(Java checking the status of threads by using another thread)

Java使用另一个线程检查线程的状态(Java checking the status of threads by using another thread)

我有一个程序,其中一堆线程执行一些任务。 我想知道所有这些线程何时完成,以便我可以用其结果做其他一些事情。 我不想使用像Thread.join这样的东西。 我更喜欢的是另一个线程检查所有这些线程,当它看到它们完成时,它执行一些特殊任务。 关于如何做到这一点的任何想法?


I have a program where a bunch of threads carry out some task. I want to know when all these threads are finished so that I can do some other stuff with their results. I don't want to use things like Thread.join. What I prefer is another thread checking on all these threads and when it sees that they are finished, it carries out some special task. Any ideas about how this can be done ?


原文:https://stackoverflow.com/questions/13000446
更新时间:2022-11-06 21:11

最满意答案

你这样开始:

int value = 123;
bgw1.RunWorkerAsync(value);  // argument: value,  the int will be boxed

接着

private void worker_DoWork(object sender, DoWorkEventArgs e) 
{
   int value = (int) e.Argument;   // the 'argument' parameter resurfaces here

   ...

   // and to transport a result back to the main thread
   double result = 0.1 * value;
   e.Result = result;
}


// the Completed handler should follow this pattern 
// for Error and (optionally) Cancellation handling
private void worker_Completed(object sender, RunWorkerCompletedEventArgs e) 
{
  // check error, check cancel, then use result
  if (e.Error != null)
  {
     // handle the error
  }
  else if (e.Cancelled)
  {
     // handle cancellation
  }
  else
  {          
      double result = (double) e.Result;
      // use it on the UI thread
  }
  // general cleanup code, runs when there was an error or not.
}

You start it like this:

int value = 123;
bgw1.RunWorkerAsync(argument: value);  // the int will be boxed

and then

private void worker_DoWork(object sender, DoWorkEventArgs e) 
{
   int value = (int) e.Argument;   // the 'argument' parameter resurfaces here

   ...

   // and to transport a result back to the main thread
   double result = 0.1 * value;
   e.Result = result;
}


// the Completed handler should follow this pattern 
// for Error and (optionally) Cancellation handling
private void worker_Completed(object sender, RunWorkerCompletedEventArgs e) 
{
  // check error, check cancel, then use result
  if (e.Error != null)
  {
     // handle the error
  }
  else if (e.Cancelled)
  {
     // handle cancellation
  }
  else
  {          
      double result = (double) e.Result;
      // use it on the UI thread
  }
  // general cleanup code, runs when there was an error or not.
}

相关问答

更多
  • 我建议您创建一些业务特定的异常,它描述了您在后台执行的操作。 并将这个异常作为内部异常抛出: private void bgWorker_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e) { if (e.Error != null) throw new BusinessSpecificException("Operation failed", e.Error); // ... } 因此 ...
  • 你这样开始: int value = 123; bgw1.RunWorkerAsync(value); // argument: value, the int will be boxed 接着 private void worker_DoWork(object sender, DoWorkEventArgs e) { int value = (int) e.Argument; // the 'argument' parameter resurfaces here ... / ...
  • 是的,.so文件需要安装到PKGLIBDIR中。 你可以通过运行“pg_config”找出PKGLIBDIR是什么。 例如,在带有PostgreSQL 9.4的Ubuntu系统上,pg_config将返回: PKGLIBDIR = /usr/lib/postgresql/9.4/lib 此外,worker_spi - 1.0.sql应安装到SHAREDIR / extension中。 在带有PostgreSQL 9.4的Ubuntu系统上,从pg_config返回的SHAREDIR是: SHAREDIR = ...
  • 我发布这个作为答案'因为评论文本太长了。 也许我错过了一些东西(以这种格式阅读代码很痛苦)。 您从1到99计数并每50毫秒报告一次进度。 在中间似乎没有任何事情发生,我的意思是工作量会增加一些真正的延迟。 然后你报告100%,然后它似乎实际上加载文件和解析,这需要一段时间,我猜。 你不应该在ParseLinks()方法的某个地方抛出一个ReportProgress()。 当然,您必须能够计算要解析的节点数,这样您才能以一定的速度报告进度,这与工作完成时的100%进度相吻合。 编写另一个递归方法,只提前计算节 ...
  • 您无法更改DoWork事件的签名,但它包含一个通用Object供您使用(称为e.Argument )。 定义一个自定义类,以包含要移入和移出BackgroundWorker所有数据。 Option Strict On Public Class Form1 Class MyParameters Friend Input As Integer Friend Output As Integer Friend Message As String End Class Priva ...
  • 您应该使用System.Threading.Tasks命名空间中的Task ,它非常简单易用。 要启动任务,您只需使用: Task.Factory.StartNew()将方法或lambda表达式作为参数传递。 你得到一个Task对象,你可以用它来继续,得到结果,等等。 You should use Task from the System.Threading.Tasks namespace instead, it's very simple and easy to use. To start a task, ...
  • 您无法在非UI线程上更新GUI控件,因此您必须在循环期间尝试“报告”调查结果。 在这里,我只使用ListBox中的字符串副本启动线程: bgw.RunWorkerAsync(ListBox1.Items.Cast(Of String)) 我们需要一个简单的类来报告信息: Public Class UserStatus Property Name As String Property Kind As Integer End Class 然后在DoWork方法中 Private Sub bgw_Do ...
  • 您无法在Invoke()方法中传递参数。 似乎你需要做的就是正确地调用你的方法(注意p ): UtilityHelper.RunWorkAsync( () => RetrieveKnownPrinters(), (p) => UpdateDataViewWithKnownPrinters(p)); 编辑:你也可以试试这个 UtilityHelper.RunWorkAsync( RetrieveKnownPrinters, Upda ...
  • 我想你只需要调用属性(伪代码): private void bgw1_DoWork(object sender, DoWorkEventArgs e) { // looping through stuff { this.Invoke(new MethodInvoker(delegate { Text = textBox1.Text; })); } } I think you need to just invoke the property (pseudo-code): private ...
  • 您必须将public修饰符添加到essentialBgWorker public BackgroundWorker essentialBgWorker = new BackgroundWorker(); You must add public modifier to essentialBgWorker public BackgroundWorker essentialBgWorker = new BackgroundWorker();

相关文章

更多

最新问答

更多
  • 如何在Laravel 5.2中使用paginate与关系?(How to use paginate with relationships in Laravel 5.2?)
  • linux的常用命令干什么用的
  • 由于有四个新控制器,Auth刀片是否有任何变化?(Are there any changes in Auth blades due to four new controllers?)
  • 如何交换返回集中的行?(How to swap rows in a return set?)
  • 在ios 7中的UITableView部分周围绘制边界线(draw borderline around UITableView section in ios 7)
  • 使用Boost.Spirit Qi和Lex时的空白队长(Whitespace skipper when using Boost.Spirit Qi and Lex)
  • Java中的不可变类(Immutable class in Java)
  • WordPress发布查询(WordPress post query)
  • 如何在关系数据库中存储与IPv6兼容的地址(How to store IPv6-compatible address in a relational database)
  • 是否可以检查对象值的条件并返回密钥?(Is it possible to check the condition of a value of an object and JUST return the key?)
  • GEP分段错误LLVM C ++ API(GEP segmentation fault LLVM C++ API)
  • 绑定属性设置器未被调用(Bound Property Setter not getting Called)
  • linux ubuntu14.04版没有那个文件或目录
  • 如何使用JSF EL表达式在param中迭代变量(How to iterate over variable in param using JSF EL expression)
  • 是否有可能在WPF中的一个单独的进程中隔离一些控件?(Is it possible to isolate some controls in a separate process in WPF?)
  • 使用Python 2.7的MSI安装的默认安装目录是什么?(What is the default installation directory with an MSI install of Python 2.7?)
  • 寻求多次出现的表达式(Seeking for more than one occurrence of an expression)
  • ckeditor config.protectedSource不适用于editor.insertHtml上的html元素属性(ckeditor config.protectedSource dont work for html element attributes on editor.insertHtml)
  • linux只知道文件名,不知道在哪个目录,怎么找到文件所在目录
  • Actionscript:检查字符串是否包含域或子域(Actionscript: check if string contains domain or subdomain)
  • 将CouchDB与AJAX一起使用是否安全?(Is it safe to use CouchDB with AJAX?)
  • 懒惰地初始化AutoMapper(Lazily initializing AutoMapper)
  • 使用hasclass为多个div与一个按钮问题(using hasclass for multiple divs with one button Problems)
  • Windows Phone 7:检查资源是否存在(Windows Phone 7: Check If Resource Exists)
  • 无法在新线程中从FREContext调用getActivity()?(Can't call getActivity() from FREContext in a new thread?)
  • 在Alpine上升级到postgres96(/ usr / bin / pg_dump:没有这样的文件或目录)(Upgrade to postgres96 on Alpine (/usr/bin/pg_dump: No such file or directory))
  • 如何按部门显示报告(How to display a report by Department wise)
  • Facebook墙贴在需要访问令牌密钥后无法正常工作(Facebook wall post not working after access token key required)
  • Javascript - 如何在不擦除输入的情况下更改标签的innerText(Javascript - how to change innerText of label while not wiping out the input)
  • WooCommerce / WordPress - 不显示具有特定标题的产品(WooCommerce/WordPress - Products with specific titles are not displayed)