Java 使片段等待线程完成

Java 使片段等待线程完成,java,android,multithreading,android-fragments,Java,Android,Multithreading,Android Fragments,在我正在开发的Android应用程序中,我有一个片段,它启动了一个线程,从中获取图像 一个特定的URL,然后在片段中的ImageView上显示该图像。 我的问题是,我的应用程序没有像我预期的那样等待线程完成 在AdvertisementFragment.java中: @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstan

在我正在开发的Android应用程序中,我有一个片段,它启动了一个线程,从中获取图像 一个特定的URL,然后在片段中的ImageView上显示该图像。 我的问题是,我的应用程序没有像我预期的那样等待线程完成

在AdvertisementFragment.java中:

@Override
public View onCreateView(
        LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

        // Obtain the advertisement controller.
        controller = new AdvertisementController();

        // Shows a spinner while fetching the advertisement image.
        progressDialog = ProgressDialog.show(getActivity(), "", getString(R.string.fetchingAdvImage));

        controller.showAvertisementImage2();

        // Destroy the spinner
        progressDialog.dismiss();

    return inflater.inflate(R.layout.fragment_advertisement, container, false);
}
控制器具有以下方法:

    public void showAvertisementImage2() {
    GetAdvertisementImageThread advertisementImageThread = new GetAdvertisementImageThread("Advertisement image thread", advertisementData);
    try {
        advertisementImageThread.t.join();
        Log.v("Thread", "Se pone en espera.");
    } catch (InterruptedException e) {
        Log.v("Thread", "Se llanza la exception.");
        e.printStackTrace();
    }
}
在GetAdvertisementImageThread类中:

GetAdvertisementImageThread(字符串threadname,AdvertisementData advertisementDataPassed){ 名称=线程名称; advertisementData=advertisementDataPassed

advertisementData = new AdvertisementData();

t = new Thread(this, name);
Log.v("Thread", "New thread: " + t);
t.start();
}


等待线程完成URL数据获取将非常缓慢,尤其是在低速互联网连接的情况下。我建议不要等待它完成,而是让它慢慢地显示一条获取数据的消息;保持用户友好。

有什么理由不使用AsynTask?为什么不使用AsynTask?AsyncTask非常简单和容易,这是第一次使用线程,Thread.join()是我找到的第一个选项,在制作了一个小示例之后,它似乎可以工作。我将检查AsyncTask选项,谢谢。不过,我还是想知道为什么不使用Thread.join()?
public void run() {
 try {

    // Connect to the url.
    in = openHttpConnection(url);

    // If the connection was no successful finish the execution.
    if (in == null) return;

    // Read the InputStream character by character and add it to the pageSourceCode String variable.
    InputStreamReader isr = new InputStreamReader(in);
    int charRead;
    pageSourceCode = "";
    char[] inputBuffer = new char[BUFFER_SIZE];
    .....
    }
}

I was expecting for the Fragment to wait for the Thread to finish but it does not and instead it destroys the 
ProgressDialog before the image is fetched and get the image afterwards. 
I thought that the .join will make it wait for the Thread to finish but it seems it does not. 
What am I doing wrong?