I had a quick question, in Java, is it better to let a thread run continuously after it is done being used, or is it better to try and .interrupt() the thread?
My thought is this: Lets say I create threads by a loop so that I can have 100 threads all doing a separate process that does not interrupt the GUI (on the main thread), then the process is finished on all of the threads. Do I stop the threads, or do I just let them continue being open, even though they are not technically doing anything?
My guess is that it would be best to kill the threads so they do not take any resources from the rest of the program. Any ideas?
When a thread has "finish processing", i.e., exits from the run method, the thread will terminate itself and there's no need to interrupt.
Related
Here is what I want to do:
There are many threads start at any time, and each thread will run about 5s. When one thread is running, others must wait. And when the running thread ends, the newest thread start to run and other waiting threads just stop.
Of course, there will be situations: when one thread start, there's no other thread.
I tried to use FutureTask, but failed. It seems too complex for me.
Can anyone give me some idea?
you might want to take a look at single-threaded executor, which will take your tasks from task queue and invoke them sequentially.
it is more convenient to use this class if you will decide later to add some concurrency
I have a class XYZ which extends Thread and it is also a singleton (Yes. My application needs that).
In the run method, I have something like this:
public void run() {
service.start();
}
The time it takes for service.start() is huge.
Also, my application will not always need the thread to be run but can't decide in advance so while launching the application I am starting this thread.
Now, when application doesn't need the thread, it gets completed very quickly and all I need to do is wait for thread to die.
I tried to use stop() method but came to know that it is deprecated.
See this article for alternatives to calling stop()
http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html
stop has been deprecated a long time ago and should not be used. Thread termination is a cooperative process in Java (i.e. the interrupted code must do something when asked to stop, not the interrupting code) - one way is to call thread.interrupt() on the thread you need to interrupt.
You then need to catch the generated interrupted exception in the running thread or check the interrupted status regularly. Once the running thread detects that is should stop what it's doing, you can then run any cleanup tasks as required and exit whatever you were doing.
Signal your thread to do it's cleanup stuff, which you said is fast anyway, then just do a Thread.join.
Your question is highly dependant on exactly what is going on in service.start(). If it's opening external resources, then naturally you can't just barge in and kill the thread without proper cleanup. The start procedure will need to be coded explicitly for interruptibility with proper cleanup.
I have implemented a multi-threaded program which involves spawning a thread for each user,and performing some minor activities(No exhaustive processes like database connection involved).The main thread runs infinitely,and its termination is handled via monitoring file creation activity.
My question is, is it okay to terminate the main thread straightaway,without waiting for the threads to finish ? (assuming that the threads would complete on their own(!),could be a false assumption).
Sure.
The main thread is just one thread amongst others and its termination won't affect the other threads (unless you don't use System.exit() to stop the thread...).
The main thread is just the first thread*) that has been started but it has no extra or hidden features or functionalities.
*) to keep it simple - the jvm may have started some internal threads before main - but the application has no code for those threads
Yes, The point of threads is that they run independently.
It would only matter if your client threads were started as daemon threads and main is the only non-daemon thread. (In which case, the application would shutdown when it stops)
Yes and usually that's the case in most applicaitons. The main thread usually is repsonibly for initiating the system and it can peacefully die after that.
Note that you don't really "terminate" themain thread, instead just let it complete its run method. And thats ok.
For example if i have a java command line program that spawns a new thread (thread #2) to do some polling, and then sleep for 5 minutes. while the main thread (thread #1) of the program is running and then finishes before the 5 minutes from thread #2 is up, so the program will exit. Is there any problem with this? Should I interrupt Thread #2 in Thread #1 before the end of the main function in this program?
It may be considered bad practice and a sign of poor design by some, but in principal there shouldn't be any problem to terminate the JVM with System.exit. Not if there is no clean-up to be performed by Thread #2.
Another issue though, is whether or not Thread #2 may be in the middle of some action.
It depends entirely on what it's doing. When the program exits, the process will terminate, taking any additional threads with it. The only potential problem would be if Thread #2 holds some resource handle. However, if all it's doing is reading, then you shouldn't have a problem.
Non-deamon threads keep on running in the background after main has finished execution.
As a result you will have hunging threads unless you explicitly call System.exit which kills all threads.
The best approach though would be to stop the thread#2.
Just use a status flag e.g. boolean die in thread#2.
Thread#1 will interrupt the thread#2, thread#2 will then see the die flag (set by thread#1) set to true, will do any clean up necessary and exit gracefully.
In your case that thread#2 is just sleeping for 5 mins and not doing anything it will be fine.
Have a look at here.
For the termination of a java program, it is necessary for all non-daemon threads to terminate first.
Once all the non-daemon threads stop their execution, the JVM will kill off all the daemon threads and thus will get shut-down.
In you case, there should not be any problem, unless and until your Thread #2 is doing some important function like handling resources.
I know that this problem is caused by the sleep or wait calling on the main thread and that the answer on how to solve this will be to put the method into a seperate thread and then make that thread sleep. But the code is a mess and don't really have the time to sort it out and split it up into separate threads and was wondering if there is any other way of doing this? Even if it is not the cleanest or most common practice for working with GUIs. I only need about a seconds pause from the method.
You can't do it without creating a separate thread. Creating a thread in Java is easy. The only thing to pay attention to is that you can only touch the UI through the main thread. For this reason you need to use something like SwingUtilities.invokeLater().
It is not possible to sleep on an event thread and not cause a GUI freeze. However in Swing, the event thread is created and managed behind the scenes - you main thread (the one originating from main() method) is not the event thread.
So, you can safely sleep on your main thread.
Using a separate thread for the code is your only solution. Every action started by the Swing thread must be delegated to a separate thread if it would otherwise block the GUI.
I wrote a super simple delay function for java that doesn't let your GUI freeze . It has worked everytime i have used it and i guess it will work for you too.
void Delay(Long ms){
Long dietime = System.currentTimeMillis()+ms;
while(System.currentTimeMillis()<dietime){
//do nothing
}
}
For eg : To delay a thread by 5 millisecods use Delay(5L)
And where would one declare this thread. Please bear in mind any, any reference to a function that contains thread sleep will cause the main thread to pause. Because the main thread will have to wait the the sub thread to pause.
The reality is that threads don't realy work as seperate independant thread because a thread must be started from another thread. In other words if you are creating desktop application, and even if you don't work with other threads, your application is a one threaded application. Now if you start working with threads & putting them to sleep, you will soon find out that that you won't be able to do anything else in the application. No & no the other threads won't even run because they are waiting the first thread to finish sleeping. Why is this? Cause the thread are sub threads of the main thread and it is the main thread that is waiting for that sleep sub thread to wake up. You can't design a threadless application either as java is single main threaded application. Any, yes any, thread further defined in your application always runs inside in the main thread.
Unless somebody can prove me wrong, you obviously whould never pause your main thread as this would lock up your app. However as soon you define another thread and suspend it with sleep() this also locks up your app as the thread was defined in subclass of the main application and therefore the main thread.
So to put a very very long story to bed, pausing a user defined thread, is almost exactly the same as if your called the Thread.sleep() for anywhere in your app, it
pauses the entire application.