I have thread in my android app which finish its task but still it is not exit , when I run it again I got error that thread is already alive
my thread
Thread mythreads = new Thread()
{
#Override
public void run() {
// do some work
// exit point
}
};
so please how can I stop this even thread finish it code execution , but when I try to run it again it give me error
java.lang.IllegalThreadStateException: Thread already started
I try to stop with it with my threadkill function code but no success
public void killthread(Thread tname){
try {
if (tname.isAlive()) {
Log.d("tag1","Thread is Alive");
tname.interrupt();
tname = null;
}
}catch (Exception e){
e.printStackTrace();
}
}
Thread objects are only meant to be started once. If you need to stop/interrupt a Thread, and then want to start it again, you should create a new instance, and call start() on it:
thread.interrupt();
thread = new YourThreadSubclass();
thread.start();
In your case you are doing Thread mythreads = new Thread() so it shouldn't be a problem at all unless you are explicitly trying to stop it before completion of the excecution.
Creating Anonymous Thread
new Thread()
{
public void run() {
//Your code
}
}.start();
Related
The Thread should end if I press a button, which sets the isButtonPressed to true.
My problem is, that if a want to start the thread with thread.start(runnable) by clicking the button, I get this: IllegalThreadStateException: Thread already started (I thought the thread was terminated after the break because the the loop is over, but it seems that I am wrong).
Thread thread = new Thread(runnable);
thread.start(runnable);
The runnable Runnable:
Runnable runnable = new Runnable() {
#Override
public void run() {
time = 10;
for (int i = 10; i <= 10; i--) {
handler.post(new Runnable() {
#Override
public void run() {
txt_Time.setText(String.valueOf(time));
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
if (isButtonPressed) {
break;
}
if (time == 0) {
resetVisibleState();
break;
} else {
time--;
}
}
}
};
Thanks for your help!
Java threads are not restartable. For what you are trying to achieve, you could create a new thread each time, or you could look at an ExecutorService. Just create a single threaded executor (Executors.newSingleThreadExecutor), and submit your runnable to it every time you need it to run.
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(runnable);
From my understanding you need to start a new thread. You cannot re-start a thread that has ran its course.
Since you are correctly stopping the old one via your isButtonPressed. You should just be able to start a new instance of the thread in its place
Take a boolean variable and wrap the contents you need to run continusly in the thread with a while loop that runs forever till Run is set to false then on clicking the button set the variable to false, for example :-
volatile boolean run = true;
Thread t = new Thread()
{
while(run)
{
// whatever is here runs till Run is false
}
}
t.start();
/*now when the button is pressed just trigger Run as false and the thread will be ended
later call t.start() when you need to start the thread again.*/
I have a thread in my android app, this thread has to sleep for a certain time in order to waiting some results which will be set by the runOnUiThread thread, the problem is when i tried to make the thread sleeps for a portion of time the runOnUiThread sleeps with it too and so it doesn't perform any processing till the other thread wakes up although runOnUiThread is exists in another separated thread.
that's my code:
The thread that contains the runOnUiThread :
Thread xbmc = new Thread (){
#Override
public void run(){
System.out.println("one");// working perfectly
runOnUiThread(new Runnable() {
public void run() {
try {
System.out.println("two");// not work till the other thread wakes up
} catch (Exception e) {
}
}
});
}
};
xbmc.start();
And this is the Thread that I make sleeps:
display = false;
Thread wait = new Thread(new Runnable() {
#Override
public void run() {
int d = 0;
while (d != 20) {
if (wake_up) {
display = true;
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
d++;
}
if (!display) {
display = true;
}
}
});
wait.start();
while(!display){}// infinite loop waits for the thread to finish it's looks or something breaks it, and there is no something can break it but the `runOnUiThread` processing results
I think you're missunderstanding some basic concepts about Threads. Your threads, as you defined them, seem (moreless) ok, they are not blocking your UI as they're running in the background. What is blocking your UI is the while (!display) {} loop.
You're waiting here until your thread modifies that value, which I guess is not what you're trying to achieve. You'd need to define some other way of doing this, like for example, append the while (!display) content code block to the Thread.
This question already has answers here:
How to properly stop the Thread in Java?
(9 answers)
Closed 9 years ago.
I am having a problem trying to stop a thread instantly after a certain amount of time has elapsed, because thread.stop and similar others have been depreciated.
The thread that I am trying to stop uses my mouse and I need to stop it so that I can use my mouse in other ways.
What I was thinking is the code below, which was just to make another thread to watch how long the main thread has been running and if it is alive, stop it, but I can't accomplish this.
public void threadRun(int a) {
Thread mainThread = new Thread(new Runnable() {
#Override
public void run() {
// does things with mouse which may need to be ended while they
// are in action
}
});
Thread watchThread = new Thread(new Runnable() {
#Override
public void run() {
if (timeFromMark(mark) > a) {
if (mainThread.isAlive()) {
// How can I stop the mainThread?
}
}
}
});
}
You need to define a class for your second thread that extends runnable and pass the first thread as an argument.
Then you can stop the first thread.
But instead of doing this manually, have a look at the Java ThreadPoolExecuter and its awaitTermination(long timeout, TimeUnit unit) method. (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html )
Will save a lot of work.
ExecutorService executor = Executors.newFixedThreadPool(1);
Runnable r = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
System.out.println("doing stuff");
Thread.sleep(10000);
System.out.println("finished");
} catch (InterruptedException e) {
System.out.println("Interrupted before finished!");
}
}
};
executor.execute(r);
executor.shutdown();
try {
executor.awaitTermination(1, TimeUnit.SECONDS);
executor.shutdownNow();
} catch (InterruptedException e) {
//
}
System.out.println("Thread worker forced down. Continue with Application...");
Produces:
doing stuff
Interrupted before finished!
Thread worker forced down. Continue with Application...
Last two messages are nearly equal in terms of time and may change positions (its two different threads, continuing)
Java has deprecated methods for explicitly killing another thread (like Thread.stop / Thread.destroy). The right way is to make sure the operations on the other thread can handle being told to stop (for example, they expect an InterruptedException, which means you can call Thread.interrupt() in order to stop it).
Taken from How do I kill a thread from another thread in Java?
Killing/stopping threads is a bad idea. That's why they deprecated those methods. It's better to ask the thread to stop. E.g., something like the example below. (But note: if "do_something()" takes a long time, then you might want to use an interrupt to abort whatever it is.)
import java.util.concurrent.atomic.AtomicBoolean;
public class Stoppable {
private AtomicBoolean timeToDie = new AtomicBoolean(false);
private Thread thread;
public void start() {
if (thread != null) {
throw new IllegalStateException("already running");
}
thread = new Thread(new Runnable() {
public void run() {
while (!timeToDie.get()) {
// do_something();
}
}
});
thread.start();
}
public void stop() throws InterruptedException {
timeToDie.set(true);
thread.join();
thread = null;
}
}
I saw this question: how to run one thread after complete another thread , but the answer to it is not appropriate for me.
I have such kind of java code for Android:
public void startTask(Runnable r)
{
running = true;
Log.i(tag, "-----------start.Runnable-----------");
Thread first = new Thread(r);
first.start();
Thread second = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
running = false;
}
});
}
first Thread takes as param Runnable object with some hard operation which I am processing in background service. So, when I call method: startTask() I set running = true; to prevent double executing tasks. But, also, I need right after completeness of first thread start second thread to set running = false; to enable other operations to execute.
How can I wait completeness of first thread by second not to freeze main thread?? Thanks!
You may use SingleThreadExecutor.
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(runnable1);
executor.execute(runnable2);
Try this:
final Thread first = new Thread(r);
first.start();
Thread second = new Thread(new Runnable() {
#Override
public void run() {
first.join();
// TODO Auto-generated method stub
running = false;
}
});
second.start();
I changed:
add final keyworrd for 'first'
wait finish of first thread by #join at begin of second thread.
start sencond thread soon.
I'm not an Android programmer but something like this may work:
private volatile boolean running = false;
public void startTask(final Runnable r)
{
running = true;
Log.i(tag, "-----------start.Runnable-----------");
Runnable runme = new Runnable() {
#Override
public void run() {
try {
r.run();
} finally {
running = false;
}
}
};
new Thread(runme).start();
}
It needs only one thread to run the task and then clear the running flag. Note the use of volatile in the declaration of running, as this variable is being read and written from multiple threads.
I have a for cylce that calls threads:
if(toModify[j]==1)
{
getUpdate(methods_list[j],username, password);
}
getUpdate is a method which contains something like this:
new Thread(new Runnable() {
public void run() {
// *** some operations***
}
}).start();
Through for cycle I can run each Thread simultaneously.
But if I want that each Thread starts only after the previous has stopped, can I use the following trick?
if(toModify[j]==1)
{
int returnValue = getUpdate(methods_list[j],username, password);
}
and add at the end of getUpdate method this code line (outside of run method):
return 1;
Using the above code each thread can start only if the previus has stopped? Or I'm wrong?
But if I want that each Thread starts only after the previous has stopped, can I use the > following trick?
This means you have a strictly sequential execution and thus the entire code can be on the same thread. What's the point of starting multiple threads if there is no parallelism?
You can use RetrantLock
private final ReentrantLock lock = new ReentrantLock();
if(toModify[j]==1)
{
lock.lock(); // block until condition holds
try {
getUpdate(methods_list[j],username, password);
} finally {
lock.unlock()
}
}
Also you will need to call join() on thread that is started from getUpdate() method.
Thread thread = new Thread(new Runnable() {
public void run() {
// *** some operations***
}
});
thread.start();
thread.join();