|
-
March 26th, 2012, 06:18 PM
#1
Threads
If I start a new thread e.g
Code:
(new Thread(new fakeClass())).start();
fakeClass {
public void run() {
System.out.println("Do I have to die?");
}
}
if I put the snipped that starts the new thread in multiple places always using new keywords will it keep creating new threads junking up my program?
-
March 27th, 2012, 01:17 AM
#2
Re: Threads
It is good to exercise caution with threads. Have as few as you can, and as many as you must. There is no automatic benefits of having multiple threads as such. When used with reason threads can provide more elegant / accesible services, when used carelessly you have services that are inefficient, where performance bottlenecks / load varies sporadically and deadlocks are rampant.
Thus, you should seriously consider using Executors to maintain your threads, and once more, consider them carefully. In that example of yours, yes used in that fashion, you always launch a new thread. Then "if it junks up your application", is another question. There will be exactly as many threads as you created, if it is "junking things", thats just bad design. If you have repetitive task such as here, you could use SingleThreadExecutor instance, rather than launching always another thread.
I suppose you know, that snipplet cannot compile.
Last edited by Londbrok; March 27th, 2012 at 01:23 AM.
-
March 27th, 2012, 12:06 PM
#3
Re: Threads
My question is.. When you create a new thread using the (runnable interface) does the program just run through what is available then end. Or is there a specified place for that thread. Meaning if I keep calling that (new Thread(new fakeClass())).start(); will it keep saving threads to memory? Or does it just go through run() and, then end when there is no code left to run?
P.S: I use threads because, I am in need of variable changes and I want my program to constanly test for variables and change them. Plus I have a couple timers that need to be run congruentl with the program for certain features.
-
March 27th, 2012, 12:38 PM
#4
Re: Threads
In simple terms when the run method exits the thread dies and all resources reserved by the thread are released. But, creating threads is expensive and therefore if you will be creating and releasing lots of threads you would be better off doing as Londbrok suggested
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|