简体   繁体   中英

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.

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.

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.

You can use while loop and isAlive() to block the thread getting terminated

Try declaring the second thread outside the run() method of the first thread, and call start() inside the run() of first thread. This might solve your problem. If it does not, there's problem in your second thread code.

Example: http://pastebin.com/rx2eYQG2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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