How to stop threads of a Java program? - java

I have made a java program with GUI and have placed a "stop" button on it. When I start the program, the main thread starts 10 threads. Now I want that whenever a user click on "stop" button, all the threads should terminate first, then the main thread should terminate. How can I do that.

It depends on how you want to the 10 threads to "terminate", and how you are running the threads.
I recommend creating an ExecutorService, and writing your "threads" as Runnable implementations. These Runnable objects should respond to calls to interrupt() on their thread of execution by aborting their task, cleaning up, and exiting the run method as quickly as possible.
Submit these Runnable tasks to an ExecutorService then call awaitTermination, all in the main thread. When the user presses the "stop" button, call shutdown or shutdownNow as desired on the ExecutorService (from the event dispatch thread).
If you call shutdownNow on the executor service, it will notify the running tasks by interrupting their threads. If you call shutdown, it will allow the tasks to complete without interruption. Regardless, your main thread will block on awaitTermination until all of the tasks have completed (or the time limit runs out).
You can, of course, create and manage of all of the threads yourself, using join. The key is to make the threads interruptible if you want to be able to stop them prematurely.

Firstly, let me note that there is a tempting method on the Thread class called stop(). Do not use it, it is dangerous.
One way of doing this is to code your 10 threads to check the interrupted status of the thread.
e.g.
while (! Thread.interrupted())
{
// Do your thread's work
}
You can interrupt each worker thread by calling the interrupt() method on the Thread object, and then calling join() to wait for the thread to actually finish.

Give all Threads a shared instance of a Boolean and let them check periodically if it is true. If it's true the Thread should return from its run method. Set this Boolean to true if the user presses the stop button and then use Thread.join() to wait for all Threads.

Thread.stop() is deprecated, and it's adviced that you use a 'running' flag that is periodically checked by the Thread so it can terminate itself when you set the the flag to false. If the Thread has long wait phases, you can interrupt() it to wake it up from a wait() state.
-> Thread.stop() int he Java API doc
After terminating your Threads by setting the running condition to false, you can have your main Thread join() the other Threads sequentially to wait for their termination.

The suspend() and resume() methods on the Thread class are deprecated because they are inherently unsave. Look at this article for information on why they were deprecated and techniques to stop threads:
http://java.sun.com/j2se/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

If your threads are waiting on an InputStream then just add some boolean flag to threads and close the stream. Threads will wakeup, check the flag and exit. Same if they are waiting on a Condition (Object.wait()), use notifyAll() and set the flag. If your threads are constantly looping (which is BAD), just set the flag :)

Related

In JAVA can we make main method wait(sleep) for sometime when certain condition is meet in daemon thread?

In my main method i have started 1 daemon thread which runs in background to check certain condition is satisfied, if satisfied then my main thread should wait for sometime and then continue.
Is it possible to do so? Controlling Main thread from another thread.
Actually am trying to automate 1 application where there are many pop-up windows displayed and I want to use 1 thread in background to check for pop-ups, if pop-ups are displayed then my main method should wait for some time then begin again.
You can simply use the wait() and notify() on a common lock object.
From inside the main method, syncronize on the lock object. Within the synchronized block start your another thread and invoke wait() on the lock object.
In the run method of your second thread , write a synchronized block on the lock object and do your processing. Once it is done you can invoke the notify on the same lock object.
Main thread can then check if the required state has been set and then further actions can be decided (if you wish the main thread to complete its execution further or again wait and let second thread again do the processing) If you wish the second thread to again do (retry) the processing then like above you can invoke the notify() on the lock object and then can then invoke wait() on the same lock object.
This is the usual way of communication between two threads. But if its only single time process and you do not want it to happen multiple times then you can simply use the join() method. Main thread can join on the second thread. Till the second thread will be processing its task the main thread will be waiting for the processing to complete. Once the second thread is executed completely (end of run () method) control will reach the maim thread.
I suggest you to have a look at these methods. consumer-producer is a famous problem to understand these methods. You can also see these in action in an answer to another post.
https://stackoverflow.com/a/42049397/504133

Select a thread in threadpool to shutdown

I currently have a threadpool with 2 fixed threads and each thread creates 2 more threads that perform task. I have it set up to where I can pass commands to stop a thread if needed.
What I'm asking is if there is a way to select a specific fixed thread from the threadpool and shut it down.
I have everything set up to shutdown the thread just need a way to select one of the two threads and shut it down and have the other one continue running.
If there is a better way to do this I'm open to other options.
Thanks
What I'm asking is if there is a way to select a specific fixed thread from the threadpool and shut it down.
Not from the pool itself, no. Remember that you don't want to kill the thread in a thread-pool since there may be more tasks to execute.
If there is a better way to do this I'm open to other options.
I'd have a volatile boolean that is being checked in the task in question so you can cause it to quit.
private volatile boolean shutdownSpecificTask;
...
// then inside of your task you'd do something like
while (!shutdownSpecificTask) {
...
}
The only operations like this that you have at the thread-pool level is to interrupt all of the running threads with a shutdownNow() or a Future.cancel(true). Both of these interrupt the thread which sets the interrupt flag and cause methods that throw InterruptedException to do so.

java + which of these will not cause the thread to stop : wait,notify,sleep,One more option

I have been asked this question, in a multiple choice question(only 1 is correct) test, but I am not sure what can be the answer to this
which of these will not cause the thread to stop ?
wait,notify,sleep,One more option provided(i dont remember)
I understand these pretty much, but not sure what is the answer of this question, and looking for the same
wait --> The thread calls wait on the object on which it holds lock and then relies on some other thread to notify it
notify and notifyAll --> notifying will wake the thread/s up and put them into runnable queue and after the thread which called the notify on the lock releases the lock, one of the thread from the runnable queue will hold the lock.
sleep --> As the name suggests will stop the processing of the thread and put it at sleep for the amount of duration specified. Until someone interrupts or timeout occurs.
So the answer is notify will not cause thread to stop.
notify will wake up the process or put it into run queue. Other two options you have given, puts the process in the wait queue.
Wait and sleep will cause the thread to temporarily cease execution.
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#sleep%28long%29
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#wait%28%29
Notify will resume execution on a thread (or threads in the notifyAll case) that had wait called on before.
Given the three options, notify would be the most accurate answer

Shutdown Executor thread after awaitConfimation

How to shutdown all threads created with ExecutorService after the
executor.awaitTermination(1, TimeUnit.DAYS);
is finished?
That's the max time threads can work, and if, in some case, any of them does not finish current task, shut it down and start again.
If awaitTermination returns true, then all the threads have been shutdown.
If awaitTermination returns false, then some of the threads are obviously not responding to interruption*, and apart from exiting the java process, there is not much you can do...
*If the tasks run by the threads are yours, make sure they respond to interruption by exiting quickly and awaitTermination will return promptly.
There is no easy way to do it. You can use a ThreadFactory which will create daemon threads, then run awaitTermination in the main thread, followed by shutdownNow. This will (hopefully) shut down the whole JVM, and there is little to nothing better than that in the given situation. Executing System.exit() is an even more drastic measure.
Note that interrupting or even stopping threads doesn't guarantee that they will actually terminate.
You can call System.exit(1) to stop the application. If you dont want to exit then you should design your tasks so that they react to Thread.interrupt properly, there is no other way.

Can I start a thread again after it has died?

If I use start() on a Thread object and the run() method returns, is it possible to call start() again?
eg,
MyThread myThread = new MyThread();
myThread.start();
// run method executes and returns in 2 seconds
// sleep for 5 seconds to make sure the thread has died
myThread.start();
I'm just wondering because my code is throwing IllegalThreadStateExceptions, so want to know if it's because you can't do the above.
No, you can't. And the Javadoc for the Thread.start() method tells you that!
From a comment:
Is there anything else I could do to re-start a thread?
You could use ThreadPoolExecutor, which would allow you to pass in tasks and let the service assign a thread to a task. When the task is finished, the thread goes idle until it gets the next task.
So, you don't restart a thread, but you would redo/resume a task.
Nope.
From the Javadoc for java.lang.Thread:
It is never legal to start a thread
more than once.
From the javadoc:
It is never legal to start a thread
more than once. In particular, a
thread may not be restarted once it
has completed execution.
See the Thread.start() javadoc for more information.
There are other ways to accomplish what you are trying to do. For example, you could use new Threads that continue the work that was done in the Thread that has finished execution. You may also want to investigate the java.util.concurrent package.
Perhaps there is a better way of doing this if you want the thread to stop and restart multiple times. I have a tile caching thread in C++ that does something similar; it pauses when it's finished, and unpaused when it's needed again. I am new to Java, but from what I can tell, you can use Object.wait() to pause, and Object.notify() to resume threads. Maybe you could check those out in the documentation and redesign your thread to pause and resume instead of exiting.

Categories

Resources