Threads usage in Application
Can any tell me that how many threads I can use in an application. I mean is the thread implementation usage is bounded to any fixed number?
Can I use the same thread for more than one time?
for example:
public Thread td;
td = new Th开发者_如何转开发read(this);
td.start();
Can I use the above thread in my same Application in the different class or method?
Please help.
Is the thread implementation usage is bounded to any fixed number?
There is no fixed number on the number of threads, but is limited to heap size allocated to the program.
Can I use the same thread for more than one time?
Of course, a same thread can be used any number of times. Check the java.util.concurrent.Executor for using thread pools.
You may have to read in-depth concepts about Threads. Its not similar to reusable chunks. Threads have lot of issues to be addressed like race conditions. You need to really know what you're doing before using them.
One can start a thread only once. To create another thread you have create another instance.
JVM doesn't enforce max number of threads but there could be other factors OS support, available resources etc. Check following question on similar lines for max threads allowed:
Java very limited on max number of threads?
About can you use Thread multiple times, You should have look at ThreadPoolExecutor which does pooling of Threads.
Thread limits in the OS and Java's implementation of threads can vary. In all cases, threads consume memory just to maintain even when they're not doing anything since the OS allocates stack for each instance. In a 32-bit Windows app, the max number of threads per process is usually 2048 because the default stack size is 1Mb so 2*2048 = 2Gb. However Java.exe on Windows has a 256Kb stack size so perhaps it can go higher.
However it is not usually necessary or desirable to spawn so many threads. Something like a web server or such like would probably use a thread pool and put sensible bounds on the maximum number of threads it allows at one time.
Only apps which have to deal with a large number of simultaneous actions (e.g. an IRC server) should consider spawning thousands of threads, and even then I question if it's a good idea. With loading balancing etc. the load can be farmed out over several PCs which is a good thing from a maintenance point of view any way.
精彩评论