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.
Related
I have a function that has inside thread that do something
public static void animate(int column,Image image)
{
new Thread(new Runnable() {
public void run() {
try {
/* Code */
repaint();
Thread.sleep(500);
repaint();
} catch (InterruptedException ex) {
}
}
}).start();
}
The animation function I summon in the updateBoard function and after this do i++.
I want to make the function animate not continue to I++ until the thread end
Inside animate fucntion i used repaint() function from swing, When i try to use .join() its block repaint() thread.
public static void updateBoard(int column, Image image) {
int i = 0;
animate(column,image);
i++;
}
Like this:
Thread t = new Thread(new Runnable(){...});
t.start();
t.join();
However, this is kind of pointless. If you are going to start a thread and immediately block waiting for it to finish you are NOT going to get any parallelism. You may as well just call the Runnable::run method in the current thread ... and avoid the (not insignificant!) overhead of creating / starting a thread.
You have a already existing thread executing updateBoard() method. Let this thread be T1.
You invoke animate() and create another thread, let this thread be T2. Now as per your question, you want to have T1 not run further until T2 completes the execution.
Thread.java defines a method join(), it allows one thread to wait for the completion of another. In your code it can be done like this.
static Thread animationThread = new Thread(new Runnable() {
public void run() {
try {
/* Code */
Thread.sleep(500);
} catch (InterruptedException ex) {}
}
});
public static void updateBoard(int column, Image image) {
int i = 0;
animate(column,image);
animationThread.join(); // this will make the thread executing updateBoard to wait until the completion of animationThread.
i++;
}
public static void animate(int column,Image image){
animationThread .start();
}
But now every thing runs one after the other, there is no use of having two threads in this case. This is similar to
public static void updateBoard(int column, Image image) {
int i = 0;
animate(column,image);
i++;
}
public static void animate(int column,Image image){
try {
/* Code */
Thread.sleep(500);
} catch (InterruptedException ex) {}
}
In this case also until unless animate method completes (without 2nd thread), i++ will not be executed. Hence for the use case in your question having a separate thread for animate does not make sense, it only adds to the overhead of creating a separate thread and context switching. Although having a separate thread for animation seems a good idea but for that you got to restructure the program you have so as the logic is based on parallel execution so as having multiple threads makes sense.
I am starting a new thread in my app's onCreate() method like so:
stepsLogger = new Runnable() {
while(!Thread.currentThread().isInterrupted()){
//my code
try {
Thread.currentThread().sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
loggerThread = new Thread(stepsLogger);
loggerThread.start();
While it is not interrupted, it is supposed to do its thing every 10 seconds.
I am logging some text at the start of the Runnable to see how often the code gets run. The first time I run the app it's fine, but every time i restart, the text gets logged more frequently which means that more threads are running.
I have tried to stop them in the onDestroy() method:
#Override
protected void onDestroy() {
super.onDestroy();
loggerThread.interrupt();
loggerThread = null;
}
How do I make sure that the old thread gets stopped whenever the app is restarted?
Thread.interrupt() will wake up a sleeping thread with an InterruptedException, so you're most of the way there already. I'd change your loop in the following way:
while (true) {
// some code
try {
Thread.currentThread().sleep(10000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // restore the thread's interrupted flag
break;
}
}
The bit about re-interrupting the thread is subtle. You can read more about it in this post from one of the primary JVM architects: https://www.ibm.com/developerworks/library/j-jtp05236/
In case this link ever dies, the gist of it is that there can be multiple "recipients" of thread interruption. Catching the exception implicitly clears the thread's interrupted flag, so it's useful to set it again.
You could use a volatile boolean variable to determine when to stop. Something like this:
class WorkerRunnable implements Runnable {
private volatile boolean shouldKeepRunning = true;
public void terminate() {
shouldKeepRunning = false;
}
#Override
public void run() {
while (shouldKeepRunning) {
// Do your stuff
}
}
}
To start it:
WorkerRunnable runnable = new WorkerRunnable();
new Thread(runnable).start();
To stop it:
runnable.terminate();
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.*/
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 want to pause and start thread untill variable standby.
But wait() and notify() is not work for me.
Is this a collect way to pause thread?
private boolean _threadIsWaiting = true;
private Object _specialObjectFromHttp;
public void methodToUse() {
Thread thread = new Thread(new Runnable() {
getParamsFromHttp();
while (_threadIsWaiting) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
convertObject(_specialObjectFromHttp);
)};
}
// Callback method (Thread wait for this.)
private void getParamsFromHttpCallBack(Object result) {
_specialObjectFromHttp = result;
_threadIsWaiting = false;
}
You could use an object to wait on, and call notify on it. I believe that to be the better approach (Actually, it is almost always better to utilize such a mechanism instead of sleeping and bool checking).
private Object _specialObjectFromHttp;
public void methodToUse() {
Thread thread = new Thread(new Runnable() {
getParamsFromHttp();
_specialObjectFromHttp.wait();
)};
}
// Callback method (Thread wait for this.)
private void getParamsFromHttpCallBack(Object result) {
_specialObjectFromHttp = result;
_specialObjectFromHttp.notifyAll();
}
In this case it seems plausible to just use the object that is being used in that control flow anyways, but you could also just add another object that has no purpose other than being waited for.
You could use a SynchronousQueue this will block until the information you need is provided. So in one thread call take, this will wait for a put on a different thread.
Both methods are blocking and no manual syncing is needed.