I have a project which requires logging in my router from time to time and make some changes. In eclipse I have a separate project which deals with all the things I need changed and I have that in the build path of my main project which is a multi threaded project. My problem is that sometimes two threads try to access the router which messes things up. Is there anything I can do that only one thread can access a certan part of my code.
This is the related code for the main multithreaded application
if (totalLogins > 10)
{
IpManager.rebootRouter();
Thread.sleep(4000);
totalLogins = 0;
composedMessagesWithThisIP = 0;
}
And in the other project this is what I have
public synchronized static void rebootRouter()
{
try
{
//code related to restart modem
}
catch (Exception e)
{
}
}
So what I have done is made the method synchronized but I believe from time to time more than one thread access the "rebootRouter" method. Which causes problems in my main application.
What is the best way and most effective way to make IpManager.rebootRouter() be executed by one thread only?
Regards!
synchronized guarantees that only one thread can enter the block at a time, but AFAIR the same thread can enter the block multiple times (so threads don't deadlock against themselves), and if a thread is blocked because another thread is in there then it may run immediately after the first thread leaves the synchronized block.
First I'd throw logging at the entry and exit points of the routine.
I'd check to see that you don't have any recursion going on, and make sure that the calls really are running at the same time. Also, remember if there's any asynchronous work or callbacks the synchronized block may be exited.
Use Semaphore from java.util.concurrent package, to restrict the Number of thread accessing the object.
Example:
Here in this code snippet, only 1 thread can access the object at a time.
Semaphore s = new Semaphore(1);
s.acquire();
synchronized(this){
// Your modem work
}
s.release();
So what I have done is made the method synchronized but I believe from time to time more than one thread access the "rebootRouter" method.
As you have marked this method as synchronized it guarantees that more than one thread can not execute this method simultaneously . It may be code in side // Your modem work has some unsynchronized stuff that may cause problem.
My problem is that sometimes two threads try to access the router which messes things up. Is there anything I can do that only one thread can access a certan part of my code.
Define "messes things up". Since rebootRouter is synchronized, only one thread can run that method at any given time. But if a thread, call it thread A, tries to invoke it while another thread (thread B) runs it, thread A will block until B returns from rebootRouter, and A will then directly call rebootRouter itself. If this is the behavior you want, your problems are elsewhere (synchronized is not broken, or someone would've noticed).
If you want thread A in the example above to not invoke rebootRouter if it is called by another thread when in the example above, you can use Lock.tryLock:
private static final Lock lock = new ReentrantLock();
public static void rebootRouter() {
if (!lock.tryLock()) return;
try {
//code related to restart modem
} catch (Exception e) {
// Note: Empty catch blocks considered bad style
} finally {
lock.unlock();
}
}
If your needs are more specific, you probably need to rephrase your question.
Related
I'm trying to test a method that does it's work in a separate thread, simplified it's like this:
public void methodToTest()
{
Thread thread = new Thread()
{
#Override
public void run() {
Clazz.i = 2;
}
};
thread.start();
}
In my unit test I want to test that Clazz.i == 2, but I can't do this because I think that the assert is run before the thread changes the value. I thought of using another thread to test it and then use join to wait but it still doesn't work.
SSCCE:
#Test
public void sscce() throws InterruptedException
{
Thread thread = new Thread()
{
#Override
public void run() {
methodToTest()
}
};
thread.start();
thread.join();
AssertEquals(2, Clazz.i);
}
public static class Clazz
{
public static int i = 0;
}
I think this is because the test main code creates a thread that is waiting (joined) to the 2nd thread, but the 2nd thread doesn't do the work, it creates another thread to do the work and then finishes, which continues the first thread, while the third thread does the Clazz.i = 2 after the assertion.
How can I make it so that the first thread waits for the thread that it starts as well as any threads that that thread starts?
Without a reference to the thread created in methodToTest, you cannot, quite simply. Java provides no mechanism for finding "threads that were spawned during this particular time period" (and even if it did, it would arguably be an ugly mechanism to use).
As I see it, you have two choices:
Make methodToTest wait for the thread it spawns. Of course, if you explicitly want this to be an asynchronous action, then you can't very well do that.
Return the newly created thread from methodToTest, so that any callers can choose to wait for it if they so wish.
It may be noted that the second choice can be formulated in a few different ways. You could, for instance, return some abstract Future-like object rather than a thread, if you want to extend the liberty of methodToTest to use various ways of doing asynchronous work. You could perhaps also define some global task-pool that you enforce all your asynchronous tasks to run inside, and then wait for all tasks in the pool to finish before checking the assertion. Such a task pool could take the form of an ExecutorService, or a ThreadGroup, or any number of other forms. They all do the same thing in the end, but may be more or less suited to your environment -- the main point being that you have to explicitly give the caller access to the newly created thread, is some manner or another.
Since your threads seems to be performing different operations, you can use CountDownLatch to solve your problem.
Declare a CountDownLatch in main thread and pass this latch object to other threads. use await() in main thread and decrement latch in other threads.
In Main thread: ( first thread)
CountDownLatch latch = new CountDownLatch(2);
/* Create Second thread and pass the latch. Pass the same latch from second
thread to third thread when you are creating third thread */
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
Pass this latch to second and third threads and use countdown in these threads
In second and third threads,
try {
// add your business logic i.e. run() method implementation
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
Have a look this article for better understanding.
ExecutorService invokeAll() API is other preferable solution.
You can't unit-test functionality that the unit does not provide.
You're saying that you want to verify that methodToTest() eventually sets Clazz.i=2, but what does "eventually" mean? Your methodToTest() function does not provide its caller with any way to know when Clazz.i has been set. The reason you're having a hard time figuring out how to test the feature is because your module does not provide that feature.
This might be a good time for you to read up on Test Driven Development (TDD). That's where you write the tests first, and then you write code that makes the tests pass. Writing the tests first helps you to paint a clearer picture of whatever it is that you want the module to do.
It also has a side benefit: If you practice strict TDD (i.e., if you never write any module code except to make a test pass), then your test coverage will be 100%.
And, that leads to another side benefit: If you have 100% test coverage, then you can refactor without fear because if you break anything at all, your unit tests will tell you so.
So I was trying to do some testing based off some things I know about the Java Memory Model (JMM) because I wanted to see how they applied to a initialization+assignment in a try-catch block with an exception thrown, and I obtained the results I wanted (not related, but I wanted to know if in a try-catch if the allocation could happen before the initialization, and in turn before some exception was thrown, could some other Thread see the uninitialized Object before the Exception was thrown - the answer seems to be no), however I encountered something odd related to my Thread running.
Basically, my Thread never seems to exit. I ran my code to completion in a debugger, and I can see the two Threads running. My main Thread being Thread, and the Thread I created Thread-1. After I complete the main method, my main Thread goes away and is replaced with DestroyJavaVM, as expected. However, Thread-1 seems to be waiting on something.
The part that really confuses me, other than the code being too simple to screw up, is that if I put a
System.out.print("");
inside of the while block, then the slow down caused by I/O seems to cause the Thread to "catch-up" on whatever it was doing, and see the interrupt. Another thing I noticed, is that if I put a breakpoint on the "finished" #println() statement, that the Thread will break on that line, and allow me to continue which causes the print statement in the standard-out, and the program exits. That doesn't make a lot of sense to me. What is happening behind the scenes that causes the created Thread not see the interrupt?
Here is the code I have for my testing, with the unimportant bits removed that were related to me testing the JMM:
public class Foo{
static Foo p;
public static void main(String [] args){
Thread t = new Thread(new Runnable(){
#Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
}
System.out.println("finished");
}
});
t.start();
for(int i = 0; i < 100000; i++){
try{
p = new Foo();
}catch(Exception pse){
}
}
t.interrupt();
System.out.println("main-method-completed");
}
}
You have probably reproduced the bug JDK-6772683 : Thread.isInterrupted() fails to return true on multiprocessor PC.
As long as the thread runs its while-loop it won't get any messages from other threads in the system. If you do, for instance, Thread.sleep(1); the thread is paused, and a context switch to something else occurs. When the thread is restored, it will get the interrupt notification from some the main loop thread.
If you want to stop the loop in the thread you could either use a volatile variable (these are written and read explcitly from shared memory and are quite expensive), or use, for instance, an java.util.conncurrent.atomic.AtomicBoolean, which at least in theory could use some less expensive method for communicate the its state between threads.
I have two blocks of code, one waits for the other to notify it.
synchronized(this) {
wait();
}
and
while(condition) {
//do stuff
synchronized(this) {
notify();
}
}
Weirdly enough that didn't wait for the notify while this did:
synchronized(objectLock) {
objectLock.wait();
}
and
while(condition) {
//do stuff
synchronized(objectLock) {
objectLock.notify();
}
}
I'm very curious about the difference of both sets, and why the first one worked while the other didn't. Note that the two blocks reside in two different threads on two different methods (if that helps).
I hope someone could explain why this is so. I edited my question so it would be more detailed.
It didn't work because you synchronized on this which in two different threads pointed to two different Thread objects.
Synchronization with wait() and notify() would only work properly when you synchronize on the same object for locking like the objectLock that you used later on.
EDIT:
If the two thread instances belonged to the same MyThread class then to achieve the effect that you thought you're code was having, you would have to acquire a lock on their class object itself:
synchronized(MyThread.class)
You can use any object you like. However, it is generally clearer to other programmers to see an explicit lock object.
My wild guess as to why this didn't work for you is you had a different this in scope. (ie, in an anonymous function/callback). You can be explicit about which this to use by appending the class name, eg, WonderClass.this - again a reason why this is not as clear. (edit: actually WhateverClass.this won't help you if this really is a different instance)
Also do read this: http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html - I generally find it easier to put all the thread-unsafe code into small synchronized methods (which do an implict lock on this)
When you say the two blocks reside in two different threads that makes me think they're not locking on the same object because this is not the same thing. When you name an explicit lock you're using the same thing to lock on.
By the way you should call wait in a loop, like this:
synchronized(someLock) {
while (!someCondition) {
wait();
}
// now the thread has the lock and it can do things
// knowing for sure that someCondition is true
}
Without this you will be vulnerable to spurious wakeups (not all notifications come from your application code) and the order in which wait and notify are called becomes problematic (if you have two threads and one notifies before the other waits then that notification never gets seen).
I'd advise using the Monitor pattern (http://en.wikipedia.org/wiki/Monitor_(synchronization)) anyway, that could save you from errors later on, especially as your use case gets more complex:
class Monitor
{
/** Initialised to `false` by default in Java. */
boolean condition;
synchronized void waitForSomething()
{
while(!condition)
{
wait();
}
}
synchronized void signal()
{
condition = true;
notify();
}
}
That way everything is nicely encapsulated and protected (I don't usually use private modifiers in examples, but you might want to enforce additional "privacy" in your code, specifically making the condition private.)
As you can observe, in my condition loop there is wait() call, as opposed to your example where you have notify() in the loop instead. In most use cases doing what you did with notify is a mistake, although I can't speak for your particular case as you didn't provide us with enough details. I am willing to bet yours is the typical one though, for which the Monitor pattern applies beautifully.
The usage scenario is along the following: thread that wants to wait for something calls waitForSomething and another thread may cause it to continue by invoking signal method which will set the condition flag.
This question already has answers here:
What's the difference between Synchronized and Lock in my example?
(2 answers)
What's the difference in using ReentrentLock and Synchronized(object)? [duplicate]
(1 answer)
Closed 5 years ago.
I made a thread pool based on the example on this page.
In the worker thread we have the infinite loop that never lets the thread die and the wait() method call that pauses the thread when there is no work to do:
while (true) {
synchronized(queue) {
loop:while (queue.isEmpty()) { // labled the loop so we can return here
try
{
queue.wait();
if(queue.isEmpty()) // check the condition predicate again
continue loop;
}
catch (InterruptedException ignored)
{
}
}
r = (Runnable) queue.removeFirst();
}
// If we don't catch RuntimeException,
// the pool could leak threads
try {
r.run();
}
catch (RuntimeException e) {
// You might want to log something here
}
The fact is that r = (Runnable) queue.removeFirst(); can throw a NoSuchElementException which is a RuntimeException if the queue is empty. And when such an exception is thrown on that line, the current thread holding the mutex dies and the pool leaks the thread. The mutex seems to be released when the thread dies.
However, if you instead of using the default synchronized keyword to synchronize the queue, use the ReentrantLock to lock and Condition for signaling and awaiting, the current thread that holds the mutex does not seem to release the lock when it interrupts unexpectedly.
So, in my case, when I checked with JVisualVM under the Threads tab I could see that the AWT-EventQueue-0 thread was wating for Thread-1 to release the mutex. But the Thread-1 died upon its way to run the task and was unexpectedly terminated (RuntumeException) and the mutex did not seem to be released.
My questions:
1) Does not ReentrantLocks being released if the thread that holds it terminates unexpectedly?
2) Is there any difference between while (queue.isEmpty()) { and if (queue.isEmpty()) { in the code snippet above? I cannot see any difference since the thread will wait in both cases. But I think the behaviour it different when using if (like if more than one thread can affect the queue).
EDIT
Java Concurrency in Practice states:
For all these reasons, when you wake up from wait you must
test the condition predicate again, and go back to waiting
(or fail) if it is not yet true. Since you can wake
up repeatedly without your condition predicate being true, you
must therefore always call wait from within a loop, testing
thecondition predicate in each iteration.
Look at my edit in the code above, now the code should be correctly as stated in Java Concurrency in Practice.
1) Does not ReentrantLocks being released if the thread that holds it terminates expectedly?
Lock release only when you call Lock#unlock() explicitly. That why recommend to invoke Lock#unlock() in finally block to prevent deadlocks in your application.
2) Is there any difference between while (queue.isEmpty()) { and if
(queue.isEmpty()) { in the code snippet above? I cannot see any
difference since the thread will wait in both cases. But I think the
behaviour it different when using if (like if more than one thread can
affect the queue).
There, no big differences in particular situation. But using while you guarantee assert in your application, you will not invoke removeFirst() when Queue is empty.
Also, PROS for using while instead of if is spurious wakeups.
notes:
If you are implementing this schema not only for education, consider using BlockingQueue. java.util.concurrent library resolved many multithread problems and in most cases you can build application based on the high level abstractions of java.util.concurrent instead of using low-level techniques such as wait()/notify().
Your code seems too complicated - I would simply write:
while (true) {
synchronized(queue) {
while (queue.isEmpty()) {
try {
queue.wait();
} catch (InterruptedException ignored) {
//don't ignore me please
//you probably should exit the loop and return here...
}
}
r = queue.removeFirst(); //Why use a cast? Use generics instead.
}
}
The only situation where queue.removeFirst() could throw a NoSuchElementException is if it is modified concurrently, which is not possible if all accesses to the queue are made in synchronized blocks.
So find the place where you access the queue without holding the lock on the monitor and you will solve your problem.
The reason why you must call wait within a loop is that wait might wake spuriously (i.e. because wait wakes up does not mean your condition has become true so you need to test it again).
As a side note, if you used a BlockingQueue you would not have to worry about those low level details and you could simply write:
while(true) {
Runnable r = queue.take(); //blocks until queue is not empty
}
Stuff in java.util.concurrent give you more flexibility and things like timed waits and try-lock/acquire methods. Also, synchronized gives you code block, unlike lock.lock()/unlock() pairs. It also tends to be more efficient when there is no contention.
Anyway, when using concurrency, one should definitely look into java.util.concurrent since many problems are solved there already.
Here is my problem: I've got a dialog with some parameters that the user can change (via a spinner for example). Each time one of these parameters is changed, I launch a thread to update a 3D view according to the new parameter value.
If the user changes another value (or the same value again by clicking many times on the spinner arrow) while the first thread is working, I would like to abort the first thread (and the update of the 3D view) and launch a new one with the latest parameter value.
How can I do something like that?
PS: There is no loop in the run() method of my thread, so checking for a flag is not an option: the thread updating the 3D view basically only calls a single method that is very long to execute. I can't add any flag in this method asking to abort either as I do not have access to its code.
Try interrupt() as some have said to see if it makes any difference to your thread. If not, try destroying or closing a resource that will make the thread stop. That has a chance of being a little better than trying to throw Thread.stop() at it.
If performance is tolerable, you might view each 3D update as a discrete non-interruptible event and just let it run through to conclusion, checking afterward if there's a new latest update to perform. This might make the GUI a little choppy to users, as they would be able to make five changes, then see the graphical results from how things were five changes ago, then see the result of their latest change. But depending on how long this process is, it might be tolerable, and it would avoid having to kill the thread. Design might look like this:
boolean stopFlag = false;
Object[] latestArgs = null;
public void run() {
while (!stopFlag) {
if (latestArgs != null) {
Object[] args = latestArgs;
latestArgs = null;
perform3dUpdate(args);
} else {
Thread.sleep(500);
}
}
}
public void endThread() {
stopFlag = true;
}
public void updateSettings(Object[] args) {
latestArgs = args;
}
The thread that is updating the 3D view should periodically check some flag (use a volatile boolean) to see if it should terminate. When you want to abort the thread, just set the flag. When the thread next checks the flag, it should simply break out of whatever loop it is using to update the view and return from its run method.
If you truly cannot access the code the Thread is running to have it check a flag, then there is no safe way to stop the Thread. Does this Thread ever terminate normally before your application completes? If so, what causes it to stop?
If it runs for some long period of time, and you simply must end it, you can consider using the deprecated Thread.stop() method. However, it was deprecated for a good reason. If that Thread is stopped while in the middle of some operation that leaves something in an inconsistent state or some resource not cleaned up properly, then you could be in trouble. Here's a note from the documentation:
This method is inherently unsafe.
Stopping a thread with Thread.stop
causes it to unlock all of the
monitors that it has locked (as a
natural consequence of the unchecked
ThreadDeath exception propagating up
the stack). If any of the objects
previously protected by these monitors
were in an inconsistent state, the
damaged objects become visible to
other threads, potentially resulting
in arbitrary behavior. Many uses of
stop should be replaced by code that
simply modifies some variable to
indicate that the target thread should
stop running. The target thread should
check this variable regularly, and
return from its run method in an
orderly fashion if the variable
indicates that it is to stop running.
If the target thread waits for long
periods (on a condition variable, for
example), the interrupt method should
be used to interrupt the wait. For
more information, see Why are
Thread.stop, Thread.suspend and
Thread.resume Deprecated?
Instead of rolling your own boolean flag, why not just use the thread interrupt mechanism already in Java threads? Depending on how the internals were implemented in the code you can't change, you may be able to abort part of its execution too.
Outer Thread:
if(oldThread.isRunning())
{
oldThread.interrupt();
// Be careful if you're doing this in response to a user
// action on the Event Thread
// Blocking the Event Dispatch Thread in Java is BAD BAD BAD
oldThread.join();
}
oldThread = new Thread(someRunnable);
oldThread.start();
Inner Runnable/Thread:
public void run()
{
// If this is all you're doing, interrupts and boolean flags may not work
callExternalMethod(args);
}
public void run()
{
while(!Thread.currentThread().isInterrupted)
{
// If you have multiple steps in here, check interrupted peridically and
// abort the while loop cleanly
}
}
Isn't this a little like asking "How can I abort a thread when no method other than Thread.stop() is available?"
Obviously, the only valid answer is Thread.stop(). Its ugly, could break things in some circumstances, can lead to memory/resource leaks, and is frowned upon by TLEJD (The League of Extraordinary Java Developers), however it can still be useful in a few cases like this. There really isn't any other method if the third party code doesn't have some close method available to it.
OTOH, sometimes there are backdoor close methods. Ie, closing an underlying stream that its working with, or some other resource that it needs to do its job. This is seldom better than just calling Thread.stop() and letting it experience a ThreadDeathException, however.
The accepted answer to this question allows you to submit batch work into a background thread. This might be a better pattern for that:
public abstract class dispatcher<T> extends Thread {
protected abstract void processItem(T work);
private List<T> workItems = new ArrayList<T>();
private boolean stopping = false;
public void submit(T work) {
synchronized(workItems) {
workItems.add(work);
workItems.notify();
}
}
public void exit() {
stopping = true;
synchronized(workItems) {
workItems.notifyAll();
}
this.join();
}
public void run() {
while(!stopping) {
T work;
synchronized(workItems) {
if (workItems.empty()) {
workItems.wait();
continue;
}
work = workItems.remove(0);
}
this.processItem(work);
}
}
}
To use this class, extend it, providing a type for T and an implementation of processItem(). Then just construct one and call start() on it.
You might consider adding an abortPending method:
public void abortPending() {
synchronized(workItems) {
workItems.clear();
}
}
for those cases where the user has skipped ahead of the rendering engine and you want to throw away the work that has been scheduled so far.
A thread will exit once it's run() method is complete, so you need some check which will make it finish the method.
You can interrupt the thread, and then have some check which would periodically check isInterrupted() and return out of the run() method.
You could also use a boolean which gets periodically checked within the thread, and makes it return if so, or put the thread inside a loop if it's doing some repetative task and it will then exit the run() method when you set the boolean. For example,
static boolean shouldExit = false;
Thread t = new Thread(new Runnable() {
public void run() {
while (!shouldExit) {
// do stuff
}
}
}).start();
Unfortunately killing a thread is inherently unsafe due to the possibilities of using resources that can be synchronized by locks and if the thread you kill currently has a lock could result in the program going into deadlock (constant attempt to grab a resource that cannot be obtained). You will have to manually check if it needs to be killed from the thread that you want to stop. Volatile will ensure checking the variable's true value rather than something that may have been stored previously. On a side note Thread.join on the exiting thread to ensure you wait until the dying thread is actually gone before you do anything rather than checking all the time.
You appear to not have any control over the thread that is rendering the screen but you do appear to have control of the spinner component. I would disable the spinner while the thread is rendering the screen. This way the user at least has some feedback relating to their actions.
I suggest that you just prevent multiple Threads by using wait and notify so that if the user changes the value many times it will only run the Thread once. If the users changes the value 10 times it will fire off the Thread at the first change and then any changes made before the Thread is done all get "rolled up" into one notification. That won't stop a Thread but there are no good ways to do that based on your description.
The solutions that purpose the usage of a boolean field are the right direction. But the field must be volatile.
The Java Language Spec says:
"For example, in the following (broken) code fragment, assume that this.done is a non-
volatile boolean field:
while (!this.done)
Thread.sleep(1000);
The compiler is free to read the field this.done just once, and reuse the cached value in each execution of the loop. This would mean that the loop would never terminate, even if another thread changed the value of this.done."
As far as I remember "Java Concurrency in Pratice" purposes to use the interrupt() and interrupted() methods of java.lang.Thread.
The way I have implemented something like this in the past is to implement a shutdown() method in my Runnable subclass which sets an instance variable called should_shutdown to true. The run() method normally does something in a loop, and will periodically check should_shutdown and when it is true, returns, or calls do_shutdown() and then returns.
You should keep a reference to the current worker thread handy, and when the user changes a value, call shutdown() on the current thread, and wait for it to shutdown. Then you can launch a new thread.
I would not recommend using Thread.stop as it was deprecated last time I checked.
Edit:
Read your comment about how your worker thread just calls another method which takes a while to run, so the above does not apply. In this case, your only real options are to try calling interrupt() and see if has any effect. If not, consider somehow manually causing the function your worker thread is calling to break. For example, it sounds like it is doing some complex rendering, so maybe destroy the canvas and cause it to throw an exception. This is not a nice solution, but as far as I can tell, this is the only way to stop a thread in suituations like this.
Since you're dealing with code you don't have access to you're probably out of luck. The standard procedure (as outlined in the other answers) is to have a flag that is checked periodically by the running thread. If the flag is set, do cleanup and exit.
Since that option is not available to you, the only other option is to force quit the running process. This used to be possible by calling Thread.stop(), but that method has been permanently deprecated for the following reason (copied from the javadocs):
This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior.
More info on this topic can be found here.
One absolute sure way you could accomplish your request (although this is not a very efficient way to do this) is to start a new java process via Runtime.exec() and then stopping that process as necessary via Process.destroy(). Sharing state between processes like this is not exactly trivial, however.
Instead of playing with thread starting and stopping, have you considered having the thread observe the properties that you're changing through your interface? You will at some point still want a stop condition for your thread, but this can be done this was as well. If you're a fan of MVC, this fits nicely into that sort of design
Sorry, after re-reading your question, neither this nor any of the other 'check variable' suggestions will solve your problem.
The correct answer is to not use a thread.
You should be using Executors, see the package: java.util.concurrent
Maybe this can help you: How can we kill a running thread in Java?
You can kill a particular thread by setting an external class variable.
Class Outer
{
public static flag=true;
Outer()
{
new Test().start();
}
class Test extends Thread
{
public void run()
{
while(Outer.flag)
{
//do your work here
}
}
}
}
if you want to stop the above thread, set flag variable to false. The other way to kill a thread is just registering it in ThreadGroup, then call destroy(). This way can also be used to kill similar threads by creating them as group or register with group.