java start one background thread after another complete

♀尐吖头ヾ 提交于 2019-11-30 16:34:12

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.

You may use SingleThreadExecutor.

Executor executor = Executors.newSingleThreadExecutor();
executor.execute(runnable1);
executor.execute(runnable2);

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!