i'm trying to stop a specific Thread
that implement Runnable
.
I already try a few things that i found while googling it, but still can't find the best answer.
I have two Class
.
1st is Timer
. This class will create a countdown. It will send a result if countdown == 0
to another class.
public class Timer implements Runnable {
public Timer(int countdown, Room room, String cmdName) {
this.room = room;
this.countdown = countdown;
this.cmdName = cmdName;
}
public void setResultThread(IResultThread resultThread) {
this.resultThread = resultThread;
}
@Override
public void run() {
for (int i = countdown; i >= 0; i--) {
countdown--;
if (i == 0) {
resultThread.setResult(true);
}
try {
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2nd is User
. I want to stop the Thread
from this class.
Thread thread;
String threadName = "player-" + user.getName();
thread = utils.getThreadByName(threadName);
if (thread != null) {
thread.stop(); // i used stop before, but i read its not a good way
thread.interrupt();
}
if (nextTurn == 4) {
// do something
} else {
int countDown = 10
//getting player name
if (playerName != null) {
String newThreadName = "player-" + playerName;
Timer timer = new Timer(countDown, room, Send.PLAYER_TIMER.toString());
thread = new Thread(timer, newThreadName);
timer.setResultThread(resultThread);
thread.start();
}
}
I'm not sure if there's something wrong with my code or something.
I tried catch the exception, but the Thread
countdown is still running. Its seems like its interrupt while the Thread
is sleep. I ever tried with volatile boolean, but I don't think is a good way to approach in this case and of course its not working either.
I used thread.stop()
before, but its not a good idea. This is the 1st time I'm using Thread
, and its still a little bit confused for me.
I will appreciate any suggestion and answer. Thanks alot.
ANSWER
I put an answer just in case there's someone have a same problem with me.
@Override
public void run() {
try {
while (countdown >= 0) {
TimeUnit.MILLISECONDS.sleep(1000);
countdown--;
if (countdown == 0) {
resultThread.setResult(true);
}
}
} catch (InterruptedException e) {
countdown = 0;
Thread.currentThread().interrupt();
//e.printStackTrace();
}
}