问题
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!
回答1:
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.
回答2:
You may use SingleThreadExecutor.
Executor executor = Executors.newSingleThreadExecutor();
executor.execute(runnable1);
executor.execute(runnable2);
回答3:
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.
来源:https://stackoverflow.com/questions/13694850/java-start-one-background-thread-after-another-complete