简体   繁体   English

创建和杀死线程与使用.notify()和.wait()

[英]creating and killing a thread vs using .notify () and .wait ()

Assuming a control thread has access to a bunch of threads and to the objects this thread would wait on. 假设控制线程可以访问一堆线程以及该线程将等待的对象。 Which one will have a greater impact in performance if I have to start and stop, what several of these threads are doing, from this single control thread ? 如果必须启动和停止该单个控制线程中的哪个线程,哪一个会对性能产生更大的影响?

Wouldn't it just be better for example to kill it via interruption and just create a new one with the same Runnable? 例如,通过中断杀死它并以相同的Runnable创建一个新的不是更好吗?

Creating (actually start() -ing) a new thread is relatively expensive, so from a performance perspective it would be better to use wait / notify . 创建(实际上是start() ing)新线程是相对昂贵的,因此从性能角度来看,最好使用wait / notify

Secondly, interrupt is not guaranteed to "stop" a thread. 其次,不能保证interrupt会“停止”线程。 The thread may choose to ignore the interrupt ... or if it is purely CPU bound, it may not notice it at all. 线程可以选择忽略该中断...或者如果它完全是CPU绑定的,它可能根本不会注意到它。

There is also a third option: use an existing thread pool mechanism. 还有第三个选择:使用现有的线程池机制。 For example, the ExecutorService API has a various implementations that provided bounded and unbounded thread pools. 例如,ExecutorService API具有各种实现,它们提供了有界和无界的线程池。 These can take care of scaling up and down, and pool shutdown. 这些可以照顾放大和缩小,并关闭池。 You use them by submit(...) -ing tasks as Runnable instances and you optionally get a Future that allows you to wait for the task completion. 您可以通过submit(...)任务作为Runnable实例进行commit submit(...)使用它们,并有选择地获得一个Future来等待任务完成。

Finally, for most concurrent programming use-cases, there are standard classes that support the use-case, and it is better to use them rather than attempting to implement from scratch; 最后,对于大多数并发编程用例,都有支持该用例的标准类,最好使用它们,而不是尝试从头开始实现。 eg using wait / notify directly. 例如使用等待/直接通知。 In your case, you probably need some kind of "barrier" mechanism: java.util.concurrent.Phaser might be the one that you need. 在您的情况下,您可能需要某种“屏障”机制: java.util.concurrent.Phaser可能是您所需要的一种。

Threads are fairly independent from one another and in most cases each thread will know better than the control thread when it's ready to terminate. 线程彼此之间是非常独立的,并且在大多数情况下,每个线程在准备终止时都会比控制线程了解得更多。 Killing a thread is very abrupt thing, it's much better to wait for the threat to terminate itself cleanly. 杀死线程是非常突然的事情,最好等待威胁彻底终止自身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM