简体   繁体   English

如何在另一个线程中启动一个线程并使它保持活动状态?

[英]How to start a Thread within another thread and keep it alive?

Inside first thread I need to create another thread. 在第一个线程中我需要创建另一个线程。

Thread thread2 = new Thread(bworker);
thread2.start(); 

The problem is that when first thread finishes it's job, thread2 get's terminated though it has more work to do. 问题是当第一个线程完成它的工作时,虽然有更多的工作要做,但是thread2会被终止。

How can I keep it alive until it finishes it's work? 在完成它的工作之前,我怎样才能让它保持活力?

I don't want to use join because it will block the flow of the first thread. 我不想使用join,因为它会阻塞第一个线程的流量。

The second thread won't be automatically terminated when the first thread finishes. 当第一个线程完成时,第二个线程将不会自动终止。 That's not how threads work. 这不是线程的工作方式。 The only thing like that is that the whole process will terminate if there are no non-daemon threads alive. 唯一这样的事情是,如果没有非守护程序线程存活,整个进程将终止。 Assuming that's not the situation here, I think your diagnostics are messed up around the second thread - or it's dying for some other reason. 假设这不是这里的情况,我认为你的诊断程序在第二个线程周围搞砸了 - 或者由于某些其他原因而死亡。

thread.isAlive() is better option to know whether a thread is alive or not. thread.isAlive()来了解线程是否处于活动状态。

You can use while loop and isAlive() to block the thread getting terminated 您可以使用while循环和isAlive()来阻止线程终止

Try declaring the second thread outside the run() method of the first thread, and call start() inside the run() of first thread. 尝试在第一个线程的run()方法之外声明第二个线程,并在第一个线程的run()内调用start()。 This might solve your problem. 这可能会解决您的问题。 If it does not, there's problem in your second thread code. 如果没有,则您的第二个线程代码有问题。

Example: http://pastebin.com/rx2eYQG2 示例: http//pastebin.com/rx2eYQG2

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

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