如何等待线程完成

时间:2015-12-15 07:57:14

标签: android multithreading join

Thread b = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    location = relocation();
                    //log("location success");

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    b.start();
    b.join();

    if (location.y>0)
     {

         location_home.x = 4.5f;
         location_home.y =  4.5f;
         location_home.theta = (float)Math.PI;
     } else
     {
         location_home.x = -4.5f;
         location_home.y = -4.5f;
         location_home.theta = 0;
     }

我使用b.join()等待一段时间,直到var位置从重定位接收值来定义location_home的值。但它错了。线程b和if语句同时运行。帮助我:( tks all

1 个答案:

答案 0 :(得分:0)

我认为如果你在这种情况下使用Asyntask会很好:

private class YourThread extends AsyncTask {
    @Override
    protected Object doInBackground(Object[] params) {
        try {
            location = relocation();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);
        //log("location success");
        if (location.y > 0) {
            location_home.x = 4.5f;
            location_home.y = 4.5f;
            location_home.theta = (float) Math.PI;
        } else {
            location_home.x = -4.5f;
            location_home.y = -4.5f;
            location_home.theta = 0;
        }
    }
}

并使用它:

new YourThread().execute();