又一个完整的Java启动一个后台线程 [英] java start one background thread after another complete

查看:374
本文介绍了又一个完整的Java启动一个后台线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了这个问题:<一href="http://stackoverflow.com/questions/4884957/how-to-run-one-thread-after-complete-another-thread">how运行后完成另一个线程一个线程,但它的答案是不适合我。

I saw this question: how to run one thread after complete another thread , but the answer to it is not appropriate for me.

我有这样那样的java的code为Android:

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;
            }
        });
}

第一个需要的参数与一些硬的操作,我在后台服务正在处理的Runnable 对象。所以,当我调用方法: startTask()我将运行=真; 以prevent双重执行任务。但是,另外,我需要第一线的完整性后立即开始第二个线程设置的运行= 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.

我如何可以等待第一个线程的完整性通过第二不冻结主线程?谢谢!

推荐答案

试试这个:

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();

我改了:

  • 添加为第一
  • 最后keyworrd 第一个线程由#join在开始第二个线程的
  • 在等待完成。
  • 在即将开始sencond线程。
  • add final keyworrd for 'first'
  • wait finish of first thread by #join at begin of second thread.
  • start sencond thread soon.

这篇关于又一个完整的Java启动一个后台线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆