'Java - stop a sleeping thread
In my java gui program, I have a button, of which upon clicking, will create a new thread that plays a song in the background. Had I not created a new thread, and just played it in the actionListener, the song would freeze up the rest of the gui to be unusable until it finished.
However, I would like a means for the user to stop the song.. which in code I would take to mean 'terminate the thread'. I've tried some online answers like the deprecated .stop() .interrupt() methods, but they don't seem to work. I think this has something to do with the fact that the thread that plays the song is in Thread.sleep() for the duration of the song.. any way to terminate a sleeping thread? -Thanks
Solution 1:[1]
Instead of sleeping, you could have your thread wait for an object to be notified with a timeout. You would then notify the object if you want the thread to wake up or interrupt it.
Solution 2:[2]
You can use interrupt method. It will give interrupt signal to sleep method. you will catch InterruptedException and it will return from method.
Solution 3:[3]
You have to use the wait() and notify() function.
wait() tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ).
notify() wakes up the first thread that called wait() on the same object.
So you can keep another button like 'resume button' which triggers the event to notify().
Solution 4:[4]
Make Use of join method in Main method of your java program. join method waits for a thread to die. Ex.
try
{
// waiting for thread t1 & t2 to complete its execution
thread.join();
thread2.join();
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("T1 "+thread.getState());
System.out.println("T2 "+thread2.getState());
op: T1 Terminated T2 Terminated
Or visit this code https://onlinegdb.com/Cr1HMdpzcg
for more Multithreading concepts visit https://www.javatpoint.com/multithreading-in-java
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kevin Kaske |
| Solution 2 | Siva Kumar |
| Solution 3 | YakuZa |
| Solution 4 | Pratik Jadhav |
