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.
}

相关问答

更多

后台工作者异常处理(Background worker exception handling)

我建议您创建一些业务特定的异常,它描述了您在后台执行的操作。 并将这个异常作为内部异常抛出: private void bgWorker_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e) { if (e.Error != null) throw new BusinessSpecificException("Operation failed", e.Error); // ... ...

向后台工作者发送参数?(Sending Arguments To Background Worker?)

你这样开始: 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 ... ...

后台工作者worker_spi示例PostgreSQL(Background Worker worker_spi Example PostgreSQL)

是的,.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是: SHARE...

WPF后台工作者和ProgressBar(WPF Background Worker and ProgressBar)

我发布这个作为答案'因为评论文本太长了。 也许我错过了一些东西(以这种格式阅读代码很痛苦)。 您从1到99计数并每50毫秒报告一次进度。 在中间似乎没有任何事情发生,我的意思是工作量会增加一些真正的延迟。 然后你报告100%,然后它似乎实际上加载文件和解析,这需要一段时间,我猜。 你不应该在ParseLinks()方法的某个地方抛出一个ReportProgress()。 当然,您必须能够计算要解析的节点数,这样您才能以一定的速度报告进度,这与工作完成时的100%进度相吻合。 编写另一个递归方法,只...

向后台工作者传递值(Passing Values To and From Background Worker)

您无法更改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 ...

背景工作者(Background worker)

您应该使用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 ...

线程和后台工作者(Threading and Background Worker)

您无法在非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 b...

用Func和Action创建一个后台工作者类(Creating a background worker class with Func and Action)

您无法在Invoke()方法中传递参数。 似乎你需要做的就是正确地调用你的方法(注意p ): UtilityHelper.RunWorkAsync<DataTable>( () => RetrieveKnownPrinters(), (p) => UpdateDataViewWithKnownPrinters(p)); 编辑:你也可以试试这个 UtilityHelper.RunWorkAsync<DataTable>( RetrieveKnownPrinters,...

来自后台工作者的文本框文本?(Textbox text from background worker?)

我想你只需要调用属性(伪代码): 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): pri...

从不同的类访问后台工作者(Access background worker from a different class)

您必须将public修饰符添加到essentialBgWorker public BackgroundWorker essentialBgWorker = new BackgroundWorker(); You must add public modifier to essentialBgWorker public BackgroundWorker essentialBgWorker = new BackgroundWorker();

相关文章

更多

java线程状态详解(6种)

java线程类为:java.lang.Thread,其实现java.lang.Runnable接口。 ...

Storm-源码分析-Topology Submit-Executor-mk-threads

对于executor thread是整个storm最为核心的代码, 因为在这个thread里面真正完成 ...

线程报错 thread

/** * 只能这么写 * 不然 腾讯微博会报Can't create handler inside ...

关于Thread类中的start()方法和run()方法

引用 public void start() Causes this thread to ...

http status 汇总

常见HTTP状态码:200 OK,301 Moved Permanently,302 Found,30 ...

一步一步掌握java的线程机制(二)----Thread的生命周期

之前讲到Thread的创建,那是Thread生命周期的第一步,其后就是通过start()方法来启动Th ...

Java 多线程编程

Java 多线程编程 Java给多线程编程提供了内置的支持。一个多线程程序包含两个或多个能并发 ...

引入thread后socket接受不了报文了

不使用线程thread可以正常接受报文,加了后就在recvfrom那里不动了,是怎么回事? usin ...

一步一步掌握java的线程机制(一)----创建线程

现在将1年前写的有关线程的文章再重新看了一遍,发现过去的自己还是照本宣科,毕竟是刚学java的人,就想 ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本