How do i stop a thread in java [duplicate] - java

This question already has answers here:
How to stop a java thread gracefully?
(6 answers)
Closed 9 years ago.
I create a thread in Java inside a button to print a simple message but I cannot stop it.
Thread a = new Thread();
a.start();
while(true){
try{
Thread.sleep(2000);
System.out.println("code");
}catch(Exception e){
}
}
when I click on it, itvstarts to print the code, but it seems to be blocked (the button). I would like to know. how can I stop the thread? And if I stop it, would be the button available again?.
I´m using netbeans 7.3, thanks.

while(true){
}
starts an infinite loop due to which all the other operations are blocked.
Remove that

Use interrupt(). Then handle the InterruptedException

The thread you are starting is not doing anything. It starts when you call a.start() and instantly terminates, because there is no code for this thread to run. Following this, the same thread that started the new one, and that is processing the click event, enters an infinite loop, so your user interface is completely blocked.
You need to give some code for the new thread to execute. To do so, you either pass the thread a Runnable or you override the thread's run() method. For example, to give it a Runnable containing the loop that prints every 2 seconds, you could do:
final Thread a = new Thread(new Runnable() {
#Override public void run() {
while (true) {
try {
Thread.sleep(2000);
System.out.println("code");
} catch (InterruptedException e) {
break;
}
}
}
};
a.start();
After that, if you ever want to stop that thread, you'd need to save a reference to the thread a in a field or something, and then call a.interrupt(). This will cause sleep to throw an InterruptedException, which will be caught and will execute break, which terminates the infinite loop and allows the thread to reach the end of the run method, which terminates the thread.
For example:
private Thread a = null;
... click handler on start button ... {
if (a == null) {
a = new Thread(new Runnable() {
#Override public void run() {
while (true) {
try {
Thread.sleep(2000);
System.out.println("code");
} catch (InterruptedException e) {
break;
}
}
}
};
a.start();
}
}
... click handler on "stop" button ... {
if (a != null) {
a.interrupt();
a = null;
}
}

You do not stop a thread in Java, you send an interrupt() signal.
The Thread may, or may no catch the signal. If it is waiting, or sleeping or joining (wait(), sleep() or join()) has been called on it), an InterruptedException will be raised.
The Thread (in its while loop) can test whether it has been interrupted by calling the isInterrupted() method and then decide to commit suicide (e.g. exit the loop).

Related

Thread.currentThread().interrupt() Not working in Android [duplicate]

This question already has answers here:
Thread.interrupt () doesn't work
(2 answers)
Closed 6 years ago.
onIncomingCall() is a overridden method from a class in third party library pjsip. This method is called when an incoming call is made using SIP. Somehow this method makes it possible for the call to be answered ONLY if the Call answering code be inside the same method or called within the same method. But I want the call to be answered when the user presses the button. I have created a call back and make the user press the button when the call comes but the call answering code is not working if its called outside of onIncomingCall() method. So I decided to put Thread.sleep(10000) in onIncomingCall() and when the user presses the button I would like to cancel this thread so that the call answering code can be executed.
I used Thread.currentThread().interrupt() but the Thread.sleep is not cancelled at all. I wrote a separate activity to test this functionality but it failed, meaning Thread.currentThread.interrupt is not working in for me at all. What is the best option to achieve this? Kindly please update me .. I am really struggling with this.
#Override
public void onIncomingCall(OnIncomingCallParam prm) {
onIncomingCallParam = prm;
try {
Thread.sleep(10000);
} catch(InterruptedException ie) {
ie.printStackTrace();
}
answerCall();
}
UPDATE:
I fixed the issue with the below approach
resetThread();
while (testThread) {
try {
Log.d(TAG,"testThread true");
Thread.sleep(1000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
Log.d(TAG,"Call Answering code");
private void resetThread() {
Thread newThread = new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(10000);
testThread = false;
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
});
try {
newThread.start();
} catch (Exception ie) {
ie.printStackTrace();
}
}
The problem here is related to the fact that you don't interrupt the right Thread, if you call Thread.currentThread().interrupt(), you will interrupt the current thread not the one that it is currently sleeping.
Here is a clear example to show the main idea:
// Here is the thread that will only sleep until it will be interrupted
Thread t1 = new Thread(
() -> {
try {
Thread.sleep(10_000L);
System.err.println("The Thread has not been interrupted");
} catch (InterruptedException e) {
System.out.println("The Thread has been interrupted");
}
}
);
// Start the thread
t1.start();
// Make the current thread sleep for 1 sec
Thread.sleep(1_000L);
// Try to interrupt the sleeping thread with Thread.currentThread().interrupt()
System.out.println("Trying to call Thread.currentThread().interrupt()");
Thread.currentThread().interrupt();
// Reset the flag to be able to make the current thread sleep again
Thread.interrupted();
// Make the current thread sleep for 1 sec
Thread.sleep(1_000L);
// Try to interrupt the sleeping thread with t1.interrupt()
System.out.println("Trying to call t1.interrupt()");
t1.interrupt();
Output:
Trying to call Thread.currentThread().interrupt()
Trying to call t1.interrupt()
The Thread has been interrupted
As you can see in the output, the thread is interrupted only when we call t1.interrupt(), in other words only when we interrupt the right Thread.
Maybe all calls has to be done on the same thread, which created library instance. Try using HandlerThread for posting it messages and handle those messages inside custom Handler instead of suspending thread.

How to restart thread without using Thread.stop()?

I have a client-server application that runs the receive method to run in a separate thread. Thread is given some time to finish the job and the thread will be checked for the status.
There are occasions when the receive method will be blocked due to packet or ACK loss. If that happens, how can I stop the thread and start it again the next attempt?
As we all know, Thread.stop() is deprecated.
You can't restart a Java thread at all, with or without Thread.stop().
You have to create a new one.
You can however reuse a Runnable.
You can use interrupts to send to the thread and handle them to do a retry. Here is a sample that will start a thread that will not quit until the boolean done is set. However i'm interrupting the thread from a main thread to make it start over.
public class Runner implements Runnable {
private boolean done;
#Override
public void run() {
while (!done) {
try {
doSomeLongRunningStuff();
} catch (InterruptedException e) {
System.out.println("Interrupted..");
}
}
}
private void doSomeLongRunningStuff() throws InterruptedException {
System.out.println("Starting ... ");
Thread.sleep(300);
System.out.println("Still going ... ");
Thread.sleep(300);
done = true;
System.out.println("Done");
}
public static void main(final String[] args) throws InterruptedException {
final Thread t = new Thread(new Runner());
t.start();
Thread.sleep(500);
t.interrupt();
Thread.sleep(500);
t.interrupt();
}
}
Whether you can do it this way or not depends on what you are calling. Your framework doing the TCP connection may or may not support interrupting.
We should not restart a thread which is not valid , once thread has comepleted its execution.

how to stop a thread with thread interrupt method

I am trying to learn thread interrupt and how to make a thread terminate without calling stop.
public class Test implements Runnable{
static Thread threadTest=null;
public static void main(String args[]){
System.out.println("Hello i am main thread");
Test thread= new Test();
threadTest= new Thread(thread);
threadTest.start();
}
private static void exitThread() {
threadTest.interrupt();
}
#Override
public void run() {
boolean run = true;
while (run) {
try {
System.out.println("Sleeping");
Thread.sleep((long) 10000);
exitThread();
System.out.println("Processing");
} catch (InterruptedException e) {
run = false;
}
}
}
}
Output
Hello i am main thread
Sleeping
Processing
Sleeping
I am unable to understand why Sleeping is printed second time and interrupted exception is thrown second time rather than first time.I have checked posts where volatile keyword is used to stop a thread in java.but i am unable to understand how that will be used in this scenario as thread gets stopped with interrupt.
In order to see the thread being interrupted instead of entering the sleep method a second time, change the while loop test in the run method to check the interrupt flag:
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
System.out.println("Sleeping");
Thread.sleep((long) 10000);
exitThread();
System.out.println("Processing");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
The thread will sleep, then set its own interrupt flag, then check the flag and terminate. InterruptedException would be thrown by the Thread#sleep method only if the thread was sleeping while the interrupt flag was set.
Your local boolean variable is not needed. If Thread#sleep throws an InterruptedException (which it won't in this example because the thread checks the interrupted flag and leaves the while loop) then the interrupt flag is cleared, restoring it in the catch block allows the while test to see that the thread was interrupted.
In real programs the thread would be interrupted from another thread, there's no reason for a thread to interrupt itself (it can just return instead).
Calling Thread.interrupt() just sets a flag for the thread. It doesn't do anything else. Only blocking methods (those usually declare throws InterruptedException) respond to that flag being set (by throwing). The flag is sticky in that it remains set until its cleared.
So the first call to the sleep method just runs normally (the interrupted flag isn't set yet). After that your code does nothing that acts on the interrupted status, until the second loop iteration where the sleep call detects the interrupted status and throws the exception.
You can use Thread.interrupted() or Thread.isInterrupted() to check the interrupted status at any time (beware that interrupted() also clears the interrupted status if it was set).
here you creating another thread Test class but "main" has its own thread , so the new thread you created is interpreted .
Here in this code you are interrupting the new created thread Thread-0 not main thread,when you execute this code you are making thread to sleep before it enters the method exitThread() ,so it is displaying the processing, but if you try to put thread sleep after you enter exitthread() you will have your answer
Like in this code:
public class Test implements Runnable {
public boolean run = true;
#Override
public void run() {
while (run) {
try {
System.out.println("Sleeping...");
exitThread();
Thread.sleep(10000);
System.out.println("Processing...");
} catch (InterruptedException e) {
System.out.println("Thread intreputted " + e);
run = false;
}
}
}
private void exitThread() {
Thread.currentThread().interrupt();
if (Thread.currentThread().isInterrupted())
System.out.println(Thread.currentThread().getName()
+ " is intreputted");
else
System.out.println("alive");
}
public static void main(String[] args) {
System.out.println("hi I am current thread------>"
+ Thread.currentThread().getName());
Test test = new Test();
Thread thread = new Thread(test);
thread.start();
}
}
Hope it will be helpfull

Threads Java Inturrupts

This is the second post I have on trying to end/quit threads using interrupts and dealing with Ctrl-c ends. I'm not sure I understand it but here is my best attempt. I need more clarity on the concepts, and please give code examples where you can.
There are two classes, the main class Quitit and another class thething. The main class.
When loading the program via the terminal (the case on Linux):
Java -jar Quitit.jar
When you Ctrl-c to close it am i correct in saying that you need to:
Runtime.getRuntime().addShutdownHook()
Your threads so that they are killed on shut down.
Is this to correct way to deal with that ?
Why does it not allow you to call a method so that it may close down gracefully?
When not shutting down via Ctrl-C and you wish to do so via Thread.Interrupt() then does the program below use it correctly ?
Am I correct in saying that Thread.Join() halts the calling thread until the targeted thread is dead before continuing?
How would you implement/call the same Runtime.getRuntime().addShutdownHook() on implements Runnable threads, instead of extends Thread ?
Quitit class:
public class Quitit extends Thread {
public Quitit(String name) {
try {
connect("sdfsd");
} catch (Exception ex) {
}
}
void connect(String portName) throws Exception {
Thread thh = new thething("blaghname");
Runtime.getRuntime().addShutdownHook(thh);
thh.start();
System.out.println("Thread Thh (thething) Started()");
while (true) {
try {
Thread.sleep(2000);
if (thh.isAlive()) {
System.out.println("Thread Thh (thething) isAlive");
if (thh.isInterrupted()) {
System.out.println("Thread Thh (thething) is Inturrupted Should be Shutting Down");
} else {
System.out.println("Thread Thh (thething) is Not Inturrupted");
thh.interrupt();
System.out.println("Thread Thh (thething) Inturrput Sent");
System.out.println("Thread Thh (thething) Joined()");
thh.join();
}
} else {
System.out.println("Thread Thh (thething) isDead");
System.out.println("Main Thread:: can now end After Sleep off 2 seconds");
Thread.sleep(2000);
System.out.println("MMain Thread:: Sleep Ended Calling Break");
break;
}
} catch (InterruptedException xa) {
System.out.println("Main Thread:: ending due to InterruptException second Break called");
break;
}
}
System.out.println("Main Thread:: Outside While(true) via Break call");
}
public static void main(String[] args) {
try {
Thread oop = new Quitit("");
Runtime.getRuntime().addShutdownHook(oop);
oop.start();
} catch (Exception ezx) {
System.out.println("Main Thread:: Not Expected Exception");
}
}
}
TheThing class:
public class thething extends Thread {
thething(String name) {
super(name);
}
#Override
public void run() {
while (true) {
try {
System.out.println("thething class:: Inside while(true) Loop, now sleeping for 2 seconds");
Thread.sleep(2000);
} catch (InterruptedException e) {
try {
System.out.println("thething class:: has been Inturrupted now sleeping for 2 seconds!!");
Thread.sleep(2000);
break; // Will Quit the While(true) Loop
} catch (InterruptedException ex) {
System.out.println("thething class:: Second InterruptedException called !!");
}
}
}
System.out.println("thething class:: Outside while(true) and now thread is dying");
}
}
OutPut::
run:
Thread Thh (thething) Started()
thething class:: Inside while(true) Loop, now sleeping for 2 seconds
Thread Thh (thething) isAlive
Thread Thh (thething) is Not Inturrupted
Thread Thh (thething) Inturrput Sent
Thread Thh (thething) Joined()
thething class:: has been Inturrupted now sleeping for 2 seconds!!
thething class:: Outside while(true) and now thread is dying
Thread Thh (thething) isDead
Main Thread:: can now end After Sleep off 2 seconds
MMain Thread:: Sleep Ended Calling Break
Main Thread:: Outside While(true) via Break call
FINISHED - BUILD SUCCESSFUL (total time: 8 seconds)
I am surprised to here that control-c is not killing your program. It does on my test programs and should under most Unix variants.
When you Ctrl-c to close it am i correct in saying that you need to (setup a shutdown hook) so the threads are killed on shut down.
No, this is not correct. Shutdown hooks are used when you want to explicitly cleanup up some processing. They have nothing to do with the running threads and how they terminate.
Why does it not allow you to call a method so that it may close down gracefully?
Because that's not it's job.
Is this to correct way to deal with that ?
I'm not sure what the "that" is. As others have mentioned, the JVM finishes when the last non-daemon thread finishes. At that point the JVM kills all daemon threads and exits. If you want a background thread to be killed on shutdown then you'd do something like:
Thething theThing = new TheThing();
// set it to be a daemon thread before it starts
theThing.setDaemon(true);
theThing.start();
If you are asking about the proper way to terminate a thread cleanly then you can either use a volatile boolean or interrupt the thread. Typically this means that the class that starts the thread, keeps a handle around do it. Since QuitIt started TheThing class it would do something like the following if it was using a volatile boolean:
void connect(String portName) throws Exception {
Thread thh = new TheThing("blaghname");
thh.start();
...
// we are ready to kill the thread now
tth.shutdown = true;
}
Then in TheThing, the run() method would do something like the following:
public class TheThing extends Thread {
volatile boolean shutdown = false;
public void run() {
while (!shutdown) {
...
// you can also test for shutdown while processing
if (shutdown) {
return;
}
}
}
}
When not shutting down via Ctrl-C and you wish to do so via Thread.interrupt() then does the program below use it correctly ?
Using Thread.interrupt() is another way you can signal your thread that you want it to shutdown. You can also use the thread interrupt flag in a similar manner to the boolean above:
void connect(String portName) throws Exception {
Thread thh = new TheThing("blaghname");
thh.start();
...
// we are ready to interrupt the thread now
tth.interrupt();
}
It is very important to realize that interrupting a thread sets a flag on the Thread. They thread still needs to handle the interrupt appropriately with code. Then in TheThing, the run() method would do something like the following:
public class TheThing extends Thread {
public void run() {
while (!Thread.currentThread().interrupted()) {
...
}
}
}
Interrupting also causes wait(), notify(), and other methods to throw InterruptedException. The proper way to deal with this is:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// catching the interrupted exception clears the interrupt flag,
// so we need to re-enable it
Thread.currentThread().interrupt();
// probably you want to stop the thread if it is interrupted
return;
}
Am I correct in saying that Thread.join() halts the calling thread until the targeted thread is dead before continuing?
Yes. Calling join() (with no arguments) will pause the calling thread until the thread it is joining on finishes. So typically you set your shutdown flag or you interrupt the thread and then join with it:
tth.shutdown = true;
// or tth.interrupt()
tth.join();
How would you implement/call the same Runtime.getRuntime().addShutdownHook() on implements Runnable threads, instead of extends Thread ?
This question doesn't make any sense. If you are asking about how to shutdown a thread if you have implemented Runnable, then the same mechanisms that I mention above would work.
Another thing that factors into the discussion of control-c is signal handlers. They allow you to catch control-c (and other signals) so you can do something intelligent with them. They are very OS dependent (of course) and if you catch the interrupt signal (SIGINT is usually sent by control-c) and don't stop the JVM, you are going to have problems.
But in any case, you can do something like the following:
...
MyHandler handler = new MyHandler();
// catch the control-c signal, "TERM" is another common kill signal
Signal.handle(new Signal("INT"), handler);
...
private static class MyHandler implements SignalHandler {
#Override
public void handle(Signal arg0) {
// interrupt your threads
// clean up stuff
// set shutdown flags
// ...
}
}
Again, I would say that it is a bad practice to catch interrupt signal (control-c) and not take the JVM down.
You have many questions in your question. If you want to gracefully shutdown threads when Ctrl-C is hit, then register a shutdown hook, and in the code of this shutdown hook, gracefully shutdown your threads.
A Thread instance can be constructed by extending Thread, or by passing a Runnable to the Thread constructor. So, if you want the code of your shutdown hook to be implemented in a Runnable, just do the following:
Runnable r = new Runnable() {
#Override
public void run() {
try {
// code of the shutdown hook: ask running threads to exit gracefully
for (Thread t : threadsToShutDown) {
t.interrupt();
}
for (Thread t : threadsToShutDown) {
t.join();
}
}
catch (InterruptedException e) {
// too bad
}
}
};
Runtime.getRuntime().addShutdownHook(new Thread(r));
Note that the above will prevent the JVM to exit if one of the threads doesn't respond to the interrupt. Introducing a timeout would be a good idea.
Also note that you must NOT start the thread that you register as shutdown hook.
When you Ctrl-c to close it am i correct in saying that you need to: Runtime.getRuntime().addShutdownHook() your threads so that they are killed on shut down.
No.
As per the docs, addShutdownHook simply registers a thread that will be run when the VM is shut(-ting) down. In theory this would be used as an application-wide finalizer; something that would run when your process is ending, to "tidy up". However there are some issues with them, similar to the reasons why finalizers are not recommended, in fact. They aren't guaranteed to run if the process is terminated abruptly, so they can't do anything critical. They run at a delicate part in the lifecycle, so they may not be able to access or interact with objects in a way that you'd expect. And they need to run quickly, else risk the process being killed before they finish.
But anyway this is completely different to what you're thinking of. When the VM shuts down, your threads will exit, without you needing to.
And besides, you have to provide an unstarted thread as a shutdown hook, so I'm slightly surprised that you don't get an IllegalThreadState exception thrown on shutdown.
When not shutting down via Ctrl-C and you wish to do so via Thread.Interrupt()
That's not the "usual" way to exit a multithreaded program either.
You have (broadly) two options:
Start your threads as "daemons", then just leave them be. The program exits when no non-daemon threads are running, so when your main thread terminates, your program will exit even though your "worker" threads are still alive. This works best of course when your
Signal to your threads that they should exit, e.g. call a stop() method that sets a boolean flag, and have those threads allow themselves to terminate. A thread stops when its run() method returns. Generally threads only keep running while they're in some sort of loop. Simply letting your thread exit the ongoing loop when its told to exit will shut it down gracefully, as typically it will finish its current "chunk of work" before checking the flag.
Interrupting a thread doesn't do what you might expect. It just sets another boolean flag internally. Many blocking operations (such as filesystem/network/database methods) will periodically check this flag and throw an InterruptedException if it is set. This allows a blocking method to exit early, but is not guaranteed if the method isn't "well-behaved".
So in your example it works because Thread.sleep() does respond to interrupts, and you then consider this a signal to exit. If however you write your own method to calculate the millionth Fibonacci number, for example, interrupting the thread would do nothing unless your implementation explicitly checks Thread.currentThread().interrupted() between each iteration.
Also, interrupts can come from almost anywhere, and it's hard to ascribe a particular "meaning" to them. Are they a signal to kill the thread? A signal to give up on the current method because the client's bored? A signal to start from the top because new data has arrived? In non-trivial programs it's not entirely clear.
A much better approach, given this, is to use boolean flags to communicate the reason, and then interrupt after setting the flag. A thread that gets interrupted should then check its state to see what just happened, and work out what to do. For example, you could code thething.run() as
private boolean keepRunning = true;
public void run() {
while(keepRunning) {
try {
System.out.println("thething class:: Inside while(true) Loop, now sleeping for 2 seconds");
Thread.sleep(2000);
} catch (InterruptedException e) {
try {
System.out.println("thething class:: has been Inturrupted now sleeping for 2 seconds!!");
Thread.sleep(2000);
} catch (InterruptedException ex)
{
System.out.println("thething class:: Second InterruptedException called !!");
}
}
}
}
And in QuitIt, set thh.keepRunning = false before interrupting it (or even better, define a method such as thh.allWorkDone() which sets the flag, and call that).
Note that there is no way to forcibly stop another thread - with good reason - you need to signal for the thread to stop, and ensure that whatever's running in the thread observes and respects that signal.
Best by huge margin - use daemon threads with no explicit termination. Next, redesign app so I can use daemon threads with no explicit termination. Absolute last resort, when no other approach is remotely possible, any kind of explicit shutdown code such has been posted here.

How can I kill a thread? without using stop();

Thread currentThread=Thread.currentThread();
public void run()
{
while(!shutdown)
{
try
{
System.out.println(currentThread.isAlive());
Thread.interrupted();
System.out.println(currentThread.isAlive());
if(currentThread.isAlive()==false)
{
shutdown=true;
}
}
catch(Exception e)
{
currentThread.interrupt();
}
}
}
});
thread.start();
The alternative to calling stop is to use interrupt to signal to the thread that you want it to finish what it's doing. (This assumes the thread you want to stop is well-behaved, if it ignores InterruptedExceptions by eating them immediately after they are thrown and doesn't check the interrupted status then you are back to using stop().)
Here's some code I wrote as an answer to a threading question here, it's an example of how thread interruption works:
public class HelloWorld {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
Thread.sleep(5000);
System.out.println("Hello World!");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
thread.start();
System.out.println("press enter to quit");
System.in.read();
thread.interrupt();
}
}
Some things to be aware of:
Interrupting causes sleep() and wait() to immediately throw, otherwise you are stuck waiting for the sleep time to pass.
Note that there is no need for a separate boolean flag.
The thread being stopped cooperates by checking the interrupted status and catching InterruptedExceptions outside the while loop (using it to exit the loop). Interruption is one place where it's ok to use an exception for flow control, that is the whole point of it.
Setting interrupt on the current thread in the catch block is technically best-practice but is overkill for this example, because there is nothing else that needs the interrupt flag set.
Some observations about the posted code:
The posted example is incomplete, but putting a reference to the current thread in an instance variable seems like a bad idea. It will get initialized to whatever thread is creating the object, not to the thread executing the run method. If the same Runnable instance is executed on more than one thread then the instance variable won't reflect the right thread most of the time.
The check for whether the thread is alive is necessarily always going to result in true (unless there's an error where the currentThread instance variable is referencing the wrong thread), Thread#isAlive is false only after the thread has finished executing, it doesn't return false just because it's been interrupted.
Calling Thread#interrupted will result in clearing the interrupt flag, and makes no sense here, especially since the return value is discarded. The point of calling Thread#interrupted is to test the state of the interrupted flag and then clear it, it's a convenience method used by things that throw InterruptedException.
Typically, a thread is terminated when it's interrupted. So, why not use the native boolean? Try isInterrupted():
Thread t = new Thread(new Runnable(){
#Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
// do stuff
}
}});
t.start();
// Sleep a second, and then interrupt
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
t.interrupt();
Good way to do it would be to use a boolean flag to signal the thread.
class MyRunnable implements Runnable {
public volatile boolean stopThread = false;
public void run() {
while(!stopThread) {
// Thread code here
}
}
}
Create a MyRunnable instance called myrunnable, wrap it in a new Thread instance and start the instance. When you want to flag the thread to stop, set myrunnable.stopThread = true. This way, it doesn't get stopped in the middle of something, only where we expect it to get stopped.

Categories

Resources