1

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!

Community
  • 1
  • 1
yozhik
  • 4,644
  • 14
  • 65
  • 98
  • 2
    Why not use [AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html)? It has method `onPostExecute` in that method you can easily start another `AsyncTask`. – Mohsin Naeem Dec 04 '12 at 02:08

3 Answers3

7

You may use SingleThreadExecutor.

Executor executor = Executors.newSingleThreadExecutor();
executor.execute(runnable1);
executor.execute(runnable2);
Ponyets
  • 336
  • 1
  • 9
6

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.
KoRoN
  • 366
  • 1
  • 10
2

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.

Julian Wright
  • 705
  • 4
  • 13
  • Thanks, but I tried this way, but it does not work in appropriate way. When I press hardware BACK button -- it runs finally not in that way I need. – yozhik Dec 04 '12 at 10:36