Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Sub-Threads From a Thread in Java

In a java program, I spawned one thread other than the main thread, and then spawned another two threads from the original thread I created(two sub threads). In all the cases I used the Runnable interface to create threads. My question is, is there a better way of doing this? Does the performance degrade when you spawn threads recursively?

like image 371
Izza Avatar asked Dec 09 '22 08:12

Izza


2 Answers

There is no such thing as a parent-child relationship between threads in Java. Once created, they have a life of their own.

Regarding performance, you may want to use an ExecutorService to control the number of threads created in your application. Too many threads will kill performance for sure. See the Executors class too.

The way you are creating threads is perfectly ok if it is only a few. Otherwise, executor services are the preferred method.

like image 54
Jérôme Verstrynge Avatar answered Dec 13 '22 23:12

Jérôme Verstrynge


There is no problem with what you are doing, no performance degradation. If you had a more complicated program with a large number of threads, you could look for utility classes in java.util.concurrent.

like image 32
toto2 Avatar answered Dec 13 '22 21:12

toto2