I am using the thread for login on Server and I want to stop the Thread as the user press back button, I am using stop() and destroy() method and these methods crashing my application, I think these Methods are depreciated that why I am facing this problem. Please Give me the way to stop thread without using stop() and destroy().
Thread.stop() is deprecated since java 1.1 (~17 years ago...). Java of this method explains the reasons in details. This means that you should never call this method. It is still there for backwards compatibility with code written when I was young.
But what to do if you want to "cancel" the operation done in thread? The answer is that you (developer) should care about this yourself. How? It depends on your application. If for example your thread opens i/o stream you can close the stream. If your thread performs series of operations in loop you should check special flag that indicates that thread should exit and update this flag according to needs of your application (in your case when user presses "back" button.
If you still have problem please try to give more details what does your thread do and you will probably get concrete recommendations how to stop it.
For background thread in android try to use service.
I mean you start a service and put a thread in that service.
If you want to stop that service then pressed back button try "Bound" Service. You will get basic idea here.
http://developer.android.com/guide/components/services.html
Only use a thread if you want to do work repeatedly for a long time. I have never needed to start a thread.
You should look at using an AsyncTask.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
It works by using a Thread from the ThreadPool. AsyncTask's are easy to stop, have a method to override for background tasks and one to override for post task work which is suitable for updating the UI (as long as the task was started by the UI thread).
Related
I need to make a thread that start at swing button push and wait for input from rs232, process it and return String to my variable. The question is how to do that?
it should be something like that:
String myOutputString = waitForInputThread();
Or if its possible in swing panel make something like listener that do something if this waitForInputThread send interrupt (for example, if get rs232 input do update a list of items in JTable).
Could you give me some clues, tutorials, examples etc ?
To avoid blocking the Event Dispatch Thread (which is the thread that updates the GUI), start a new thread to interact with the RS232. The SwingWorker class is one option, but you can just as easily use a normal thread.1 Blocking the EDT causes your GUI to freeze, so it must never be used for lengthy tasks.
Once your result is computed, update the GUI using SwingUtilities.invokeLater(). This ensures the GUI change occurs on the EDT.
1 I tend to find normal threads executed via an ExecutorService are better for unit testing (as you can write an ExecutorService that immediately executes the Runnable, avoiding any nasty thread issues with JUnit).
It seems I miss a certain point in Java and Swing. The issue is as follows:
I have a swing GUI with a Start / Stop button (And some more)
It starts the function (What is set up as a thread in this case), Thread starts, it works, Swing GUI is fully operational and does all the other things it is made for, e.g. modifying parameters for the worker thread.
Of course, sending an interrupt to ask the thread to stop on users request is in and functions. So far so good.
But I did not found a way that Swing GUI notices the thread stopped on its own:
If I ignore it, it confuses the user.
I of course put a loop in, where Swing GUI regularly asks if Thread.isAlive (And sleeps some time to ask again), but this loop completely blocks Swing GUI.
Ideally, I would like to get a notification or an event that the thread has stopped.
Just like all the other events, Swing processes:-) .
What is the proper way to set it up?
Have a look at the SwingWorker. It is designed to perform tasks on the background as the result of a Swing event such a button press. It has hooks to listen for when the task finishes.
use a boolean flag 'done' private field. initialize done=false; when your thread run() method is complete set done=true inside thread run() method.
monitoring the value of the flag 'done' will tell you when your thread has finished.
I have a start and stop button. I want to be able to start and stop a task as many times as the user wants to. I was able to get this working properly with a regular thread by doing a wait() when the stop button was pushed and then a notify() when the start button was pushed to start the thread again. This worked great. However... I extended thread. My boss told me to never extend thread and that I should use a SwingWorker. But I noticed that a SwingWorker can only be executed once. Or can it be executed more than once in the same session..?? Can somebody help me in the right direction here?
You very rarely need to extend Thread. What you should do is pass a Runnable to a Thread constructor.
For my tastes SwingWorker adds too much coupling to code, and should be left to demos where it works very well.
You can just create a new instance of your SwingWorker each time you want to run the logic. Personally, I don't see much benefit to SwingWorker for your problem as you described it. Not to say it won't do fine...
You don't need a SwingWorker for what you doing. SwingWorker is used for cases when you have to run something in background thread, update your GUI (like progress) without locking i down.
What you did already is fine.
I am currently developing Android app, it needs download content from internet. I use thread to do that and then call runOnUiThread method to update GUI.
I placed a refresh menu on it, if user tried to refresh the content, the download thread will be created and started. The problem is that how can I control the thread order, I need to accept the latest request's response and abandon previous thread requests if there were some other requests still running because the request parameters may have been changed by user. Currently I was using a threadId to do this thing, when a thread finished, it will check its threadId, if it was the latest recored one, it then takes control and render the response. My question is that is there any other proper better solution for this?
Do I need to stop threads when user exit the app? I remember that some book said that do not try stop thread manually and wait itself finish is a good practice, is that true? Should I stop them by calling "stop" or "interrupt" method?
I read some documents around threading in Android and found the class HandlerThread, what is it? In what kind of situation I need to use it?
Rather than starting a new thread for every refresh action I would create a single thread for all the background download work that loops and downloads content as lined up in a queue. That ensures that you don't download content concurrently and also saves resources.
In the GUI you simply queue a refresh request whenever the user prompts you to and can abort a running download by calling HttpRequestBase.abort on the http method instance. The background thread should receive and catch a SocketException and move on to the next queued request.
To end the background thread you just have to end its loop. You can use the Looper and Handler classes to help you with all of the above, the HandlerThread class you mentioned is simply a handy class to create a thread that has a Looper.
The problem with interrupting a thread is that it won't break you out of a blocking I/O request and handling an InterruptException correctly can be complicated. So depending on the situation I would say yes, it is better practice to end the thread by returning from its run method.
i discover this week AsyncTask, and i replace Thread by AsyncTask in some place in my program,
You have doc & sample here, really easy to use :
http://developer.android.com/reference/android/os/AsyncTask.html
when i was using thread GUI was lock, and now it's not locked.
And it's possible to cancel a AsyncTask (but i never try)
You can use an IntentService to start your background operations, the service will operate as "work queue processor" and will execute your calls in order.
I am writing an application in java (1.6) using swing. I currently have a JXBusyLabel on a JXLayer over the content area of my program acting as a busy indicator. I want to provide a way to allow others working with me to create a task that pops up the busy label while it's executing. The catch is, the task must be cancel-able. What is the best way to expose the functionality I desire?
Some ideas I've come up with:
Raw access to setBusy()
This is obviously the easiest for me but requires users know and understand swing threading issues.
public <T> Future<T> execute(Callable<T>)
Wraps the callable in a FutureValue that is run() on a separate thread and returns that FutureValue. The question then becomes, how to keep track of all FutureValue's generated and how to ensure that they can be cancelled. (e.g. cancel(true) always cancels)
I have never used the concurrency package in Java before and it didn't exist back when I 'learned' Java. So I am open to completely new and different ways of implementing this functionality.
Edit:
Clarification of my question. I know about SwingWorker. I've just never used it. What I want to know is this:
Given a Callable (Java version of a closure?) How can I:
Return the value of call() to the user w/o blocking (I think I need to use a Future for this)
Tell the JXLayer to lock (starts painter), execute the supplied callable, and then unlock the JXLayer (stops painter)
Ensure that, no matter what thread calls my busyExec() function, the GUI remains responsive and the background task completes. (NOTE: If I return some sort of Future object and they call get() on the event thread, it can/will block and that is ok)
I guess my main stumbling point is how to implement #2. Should I have busyExec() spin off a new thread that blocks until no background tasks are running? Should I try for some sort of queue. Is there an object that will do this all for me already?
The SwingWorker (of Java 6) implements Future so it seems like it has the ability to cancel tasks via the cancel method.
More information on SwingWorker from The Java Tutorials:
Lesson: Concurrency in Swing
Worker Threads and SwingWorker
Canceling Background Tasks
Okay. For anyone interested here is what I am currently using to implement my request.
I have a method that will take a Callable<T>. It then creates a FutureTask<T> this will be returned to the caller as a this as a Future<T>. The JXBusyLabel and JXLayer are told to start painting and to lock the ui. The FutureValue and Thread (see below) is enqueued in a special list. A Runnable is created that: calls run() on the FutureTask, removes the FutureValue (and thread) from the list, and if the list is empty, unlocks the JXLayer and stops the JXBusyLabel. This Runnable is launched in a new Thread with normal priority.
When the user hits the cancel button. The list is iterated over and the FutureTasks are all canceled and removed from the list if they could be cancelled. First try cancel(false), then cancel(true). If both those means fail, the user is prompted with a warning asking them if they want to Thread.stop() the task and explains that this could make the app unstable. If yes, stop() the thread running the task. This might bring the app down. In all cases, the UI is unlocked.
The documentation for other team members states that they must be aware that the task can be killed. They are not to call get() until isDone() is true. They are explicitly told that this will basically force them to block until the task is done or cancelled. So they can't call it from the event dispatch thread.
Other solutions are still welcome