I am writing a method for my android app where I make a RecyclerView invisible, and a ProgressBar visible. I then perform some logic, before resetting the two views to their original visibility state.
With just the setVisibility() call, it works as intended. However, I am also required to call Thread.sleep() to force a wait directly after performing the logic.
Initially, I have had trouble trying to call setVisibility() to begin with. It simply did nothing. I have found many questions with similar problems, but not similar enough; I was unable to find a solution specific to my problem.
Creating a new method to simply call setVisibility(), I found that this worked as intended. I started to move my logic over, line by line, until it stopped working.
As it stands, it still technically sets the visibility correctly. However, despite being several lines down from the setVisibility() calls, my Thread.sleep() seems to be forcing itself to run before setVisibility(). I believe this was my original problem; Logically, the commands after Thread.sleep() would run directly after, and effectivley undo my setVisibility() on the very next frame.
This is my method:
public void SetMainInvisible(){
mRecyclerView.setVisibility(View.INVISIBLE);
mMainProgressBar.setVisibility(View.VISIBLE);
mTrainAdapter.RefreshAll();
Log.d("TEST", "FINISHED VIS");
try {
Thread.sleep(sSleepTime);
} catch (InterruptedException exception) {
// In the nature of a simple "Thread.sleep", there is no real reason to respond
// directly to interruption. If the sleep request is interrupted, the best course
// of action to preserve user experience is to simply move on. That said, we will
// still "re-enable" the flag that tells us the thread was interrupted, in case we
// should need to clarify if there was an interruption, later on. As is, this flag
// will be reset to false as soon as the exception is thrown.
Thread.currentThread().interrupt();
}
}
From my direct observation, when it calls, my log prints "FINISHED VIS". My application then enters the Thread.sleep() stage, and waits for 3 seconds. My views then change their visibility, as directed by the very first lines. I do not have setVisibility() anywhere else in my code.
I have tried reading further on Thread.sleep, but all references suggest exactly what I have been taught; when it executes, it forces the process to "sleep" for a set period of time. It should not force the method to postpone all other logic until it returns. On the contrary, the examples at Tutorial Point provide logic and output that suggests normal operation.
I know that I should never really be calling Thread.sleep(), but it is a direct requirement of the exercise I am completing for University. Why is Thread.sleep() forcing itself to run before any other command, despite being at the end of the method?
Changing visibility (or any other layout/drawing operation) does not have any immediate, synchronous effect on your user interface. Instead, essentially just a message is posted on the UI thread's message queue to take care of the change later.
Calling sleep() on the UI thread is a no-no. You're blocking the UI thread and execution does not return to the message handler that would take care of the relayout/redraw messages waiting in the queue. Only after the sleep() does the execution return to the message handler.
If you need to add delays to your code, use e.g. Handler#postDelayed() to post a Runnable of your own to the UI thread's message queue to be executed after a delay.
Working off #laalto's answer, I decided to test my method in the form of an AsyncTask, before looking into Handler#postDelayed() (This is something we have not covered, and I am completely unfamiliar with it). I am happy to report that it works exactly as intended.
This might be a suitable alternative, for those that are more familiar with implementing AsyncTask.
First, I implement an inner asynchronous class as follows:
private class RefreshTimesAsyncTask extends AsyncTask<Void, Void, Void> {
private long mSleepTime;
public RefreshTimesAsyncTask (long sleepTime) {
mSleepTime = sleepTime;
}
#Override
protected void onPreExecute() {
mMainProgressBar.setVisibility(View.VISIBLE);
mRecyclerView.setVisibility(View.GONE);
mTrainAdapter.RefreshAll();
}
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(mSleepTime);
} catch (InterruptedException exception) {
// ...
Thread.currentThread().interrupt();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
mMainProgressBar.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
}
}
I then simply call new RefreshTimesAsyncTask(sSleepTime).execute();, rather than my previous function call of SetMainInvisible(). I also set static long sSleepTime=3000 in the variable declaration of my main class, due to the nature of being required to set this value as a static, and not being able to declare static variables in an inner class.
Related
Im going through concurrency documentation and I can't quite understand what they mean with:
In an applet, the GUI-creation task must be launched from the init method using invokeAndWait; otherwise, init may return before the GUI is created, which may cause problems for a web browser launching an applet. In any other kind of program, scheduling the GUI-creation task is usually the last thing the initial thread does, so it doesn't matter whether it uses invokeLater or invokeAndWait.'
-What is the problem with the init being returned before GUI-creation?
-Why is the GUI-creation usually the last thing a thread does?
Tasks on the event dispatch thread must finish quickly; if they don't, unhandled events back up and the user interface becomes unresponsive.'
-How can you make it finish faster?
http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TumbleItemProject/src/components/TumbleItem.java
-Where is the EDT in the above example?
SwingWorker worker = new SwingWorker<ImageIcon[], Void>() {
#Override
public ImageIcon[] doInBackground() {
final ImageIcon[] innerImgs = new ImageIcon[nimgs];
for (int i = 0; i < nimgs; i++) {
innerImgs[i] = loadImage(i+1);
}
return innerImgs;
}
#Override
public void done() {
//Remove the "Loading images" label.
animator.removeAll();
loopslot = -1;
try {
imgs = get();
} catch (InterruptedException ignore) {}
catch (java.util.concurrent.ExecutionException e) {
String why = null;
Throwable cause = e.getCause();
if (cause != null) {
why = cause.getMessage();
} else {
why = e.getMessage();
}
System.err.println("Error retrieving file: " + why);
}
}
};
-Why is initialisation of 'worker' here followed by the overwriting of several methods instead of just ';'? I have never seen this kind of notation before...
-Are all methods that aren't the 'doInBackGround()' method ,executed under the event dispatch thread?
'All concrete subclasses of SwingWorker implement doInBackground; implementation of done is optional.'
-In the code example ,I don't see a subclass for SwingWorker , unless new SwingWorker <>() , counts as a subclass?
'Be careful when invoking either overload of get from the event dispatch thread; until get returns, no GUI events are being processed, and the GUI is "frozen". Don't invoke get without arguments unless you are confident that the background task is complete or close to completion.'
-How would you use get() in a non-EDT way ?
My apologies if some questions are obvious and thank you for your time!
What is the problem with the init being returned before GUI-creation? -Why is the GUI-creation usually the last thing a thread does?
It says it right there in the text. "It might cause problems for browsers". It may be because the caller of init requires the method to create a GUI and schedule it for gui messages, and if none is created the caller fails.
How can you make it finish faster?
It's not about making the threads run faster, it's rather that if you have a long-going task, do it in a background thread instead of the event (GUI) thread as to not make it freeze.
Where is the EDT in the above example?
It's nowhere.. The applet has a EDT which is used when you for instance click a button or interact with the applet in other ways. I don't really understand your question here.
Why is initialisation of 'worker' here followed by the overwriting of several methods instead of just ';'? I have never seen this kind of notation before... -Are all methods that aren't the 'doInBackGround()' method ,executed under the event dispatch thread?
It's an anonymous class declaration of the SwitchWorker class. No, the doInBackground does not execute on the EDT, it's performed in the background. done is however scheduled on the EDT. See http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html for reference.
In the code example ,I don't see a subclass for SwingWorker , unless new SwingWorker <>() , counts as a subclass?
It does.
How would you use get() in a non-EDT way ?
As the documentation specifies:
get()
Waits if necessary for the computation to complete, and then retrieves its result.
So you should not call it until the background method completes, as to avoid freezing of the GUI.
I was looking at the current thread:
How to create a thread that waits for a boolean variable to become true?
Everyone seemed to disagree with each other and noone exaplined themselves enough so I shall present this in the easiest way. Here is my code as of today.
boolean connecting = false;
public static void main(String[] args) {
initUI();
while(true) {
if(connecting) {
connecting = false;
doSomething();
}
};
}
initUI() is a mthod which initiates the User Interface. When the user clicks a button in that class called "Connect" it will call it's action listener and set the boolean "connecting" to "true". When it enters the if area it will then reset the boolean to "false" and run the code which I want.
This works, however... It uses far too much CPU.
If I directly set the buttons action listener to the doSomething() method the program jams (and should) as the action listener method needs to finish in order for the button to reset. However the doSomething() has loops (it's a chat program) so it will not return to the original while (which is displayed here in code) until he disconnects.
So my question, is there anyway to "wait" for the boolean to change to true. For example a listener?
ANSWER: Thanks to Joni I implemented a Thread.
The buttons actionListener now includes:
(new connectThread()).start();
And my thread looks like this:
public class connectThread extends Thread {
public void run() {
ui.btn.setEnabled(false);
doSomething();
ui.btn.setEnabled(true);
}
}
As for the question title, waiting for a boolean to change, as another person explained an event listener could be set.
So my question, is there anyway to "wait" for the boolean to change to true.
You can't do it (efficiently and responsively) with a bare boolean variable. A sleep / test loop is a poor solution because it will either be expensive or non-responsive. If the sleep interval is small you waste CPU, and if you make it larger your application takes a (relatively) long time to notice the state change.
But if the boolean is updated via a method (e.g. a setter) then you can code the setter to:
notify other threads that are waiting in a mutex; e.g. https://stackoverflow.com/a/12884570/139985, or
call some "event listener" callback.
Go back to the code where the event listener calls doSomething(), but with one change: start a new thread that runs doSomething() rather than call it directly. You can find a complete example of how to do this in the Java Tutorial: Simple Background Tasks. The SwingWorker API documentation also has an example.
You are on the wrong track - "busy waiting" as you are doing here is almost always the wrong idea, since it just needlessly burns CPU time.
From what I understand you want to react to a button-press without locking up the UI thread. There is no need to have the thread already waiting before that point - just start it up once the button is pushed, as Joni suggests. If you want to ensure that only one button press is processed at a time, you could use a thread pool with a single thread (see SingleThreadExecutor).
I also want to point out an important mistake in your example code: connecting needs to be made volatile to tell the compiler that the value could change from another thread. As it is, there is no guarantee that your worker thread will ever see the value change, so it could just loop infinitely even if you set connecting to true in another thread.
You can either put in a Thread.sleep(100); in the loop, so it's not a tight loop like that, which can easily freeze the rest of the threads.
What you can also do is use a wait/notify mechanism. Just have a shared Object, signaller... have the "while(true)" call "signaller.wait()", then, after your other thread sets the flag (it might not need to), it can call "signaller.notifyAll()" which will let the other thread run its next iteration, and see that the flag is set.
In your listener, instead of setting a flag, you could run doSomething() in a new thread. In the example below, ThreadTest is actually the class where you currently have your listener method (I've called it onClick()).
public class ThreadTest {
private ExecutorService service;
public ThreadTest() {
service = Executors.newFixedThreadPool(10);
}
// Button click listener.
public void onClick() {
service.submit(new Runnable() {
#Override
public void run() {
doSomething();
}
});
}
public void doSomething() {}
}
I have been messing around a bit with the runOnUiThread method. And if I simply make a method in my activity:
public void Test()
{
runOnUiThread(new Runnable()
{
public void run()
{
Log.v("mainActivity", "test");
}
});
}
I noticed that this runnable only runs once. However, this is not a problem. What I was wondering is if I have completely missed something and it does something in the background that would cause a frame rate drop when I have executed the method a couple times.
This is the full body from Activity.runOnUiThread(Runnable):
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
The method body is still executed in your background thread, and mHandler of class android.os.Handler implements an internal queue for Runnables posted to it, so unless you're doing blocking work in the Runnable (which is a big no-no on the UI Thread) or calling this method upwards of a thousand times in a short period, you should not see any difference.
Now, if you were calling Handler.postAtFrontOfQueue(Runnable), then there'd be an issue, because your Runnable is essentially "cutting in line". In this case, that would likely cause a stutter, because your Runnable is being executed instead of any UI updates that needed to take place (like scrolling).
Note that you only need to run UI updates on the UI thread, like calling any methods on a View (thus the name "UI Thread" and why this method exists) or any operation where the documentation explicitly states that it needs to be run on the UI thread. Otherwise, if you're already on a background thread, there's no real reason to leave it.
It's unlikely that it would cause any significant interruption to your UI process, but there's really no point in running it on the UI thread.
If you are doing any significant amount of work, you should make sure that you do not do it on the UI thread.
I am using an API in a Java library which is called from the event dispatch thread and requires me to return a fully-initialized UI component. It looks like this:
public JDialog createDialog();
But I can only populate the dialog after loading from a database, which can take 10 seconds sometimes. Normally I would do that in a background thread but since this method is called from the EDT and since I have to return the dialog, that won't work. It's a third-party library so I can't change the method, but is there anything I can do to avoid blocking the EDT?
"Initialized" is not necessarily the same thing as "Populated". "Initialized" usually means that the object has been fully constructed, but may not have any data. "Populated" of course means that the data is present and any data-fetching tasks are complete. So it is possible to give your third-party library a fully initialized JDialog without any data at all.
The way I always like to solve this problem is to create a custom JDialog which displays a busy message or a progress bar or the like, and then request the data in another thread. When the data is returned, I replace the busy message with the data(On the EDT!). As to how you should perform your request in a background thread, I recommend using SwingWorkers. I like to use a private SwingWorker inside my custom JDialog which handles the request in the doInBackground() method, and handles the Display-related tasks in the done() method. Doing it this way will ensure that display-related tasks only occur on the EDT, and database-related tasks only occur OFF the EDT. If you'd like a reasonably good introduction to using SwingWorkers, check out Sun's tutorial on worker threads. A simple example would be:
public class DBDIalog extends JDialog{
private JLabel busyLabel = new JLabel("Fetching data from DataBase");
public DBDialog(){
//do your initialization stuff here
}
private class DBFetcher extends SwingWorker<Void,DBInfo>{
#Override
protected DBInfo doInBackground() throws Exception{
return fetchDataFromDB(); //or whatever database call to make
}
#Override
protected void done(){
try{
DBInfo info = get();
//replace your busy label with your DBInfo
}catch(InterruptedException e){
//do appropriate thread interrupted stuff
}catch(ExecutionException e){
//do appropriate general error handling stuff
}
}
}
}
A few things to remember, though: the done() method is NOT abstract, so you aren't required to override it. You should, though. If your doInBackground() implementation throws an exception, that exception will be swallowed unless done() has been overridden. Also, don't make changes to your GUI from inside the doInBackground(), unless you use SwingUtilities.invokeLater(Runnable), as doInBackground() is executed from a different thread than the EDT and making GUI changes from a background thread is asking for strange and inexplicable bugs.
When should this be used? Unlike other programming tasks, the point at which something takes too long to respond is a lot shorter in GUIs--The number I've usually seen written down is about 250ms. If your task takes longer than that, it should be in a background thread. In your case, 10 seconds should definitely be in a background thread, but then you already knew that :)
EDIT:
Seeing your comment, I see that most of my post is pretty moot. However, you can still use a SwingWorker:
Have your SwingWorker perform the data-retrieval, and in the done() method, have it construct the JDialog from the data and hand that dialog to your third-party library.
Construct the dialog without data, and then start a task to populate it.
From a user-experience perspective, anything that takes 10 seconds from initiation to completion is going to be an issue. It's best if you should them something right away, even if it's not in final form. If necessary, you could pop a modal dialog that simply says "Loading."
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.