使用AsyncTask()进行多线程处理:使用wait()和notify()

时间:2013-06-20 01:30:20

标签: java android android-asynctask wait notify

我很难理解多任务在Java中是如何工作的。我在这里读了一些关于SO的文章,但仍然有问题。

我有我的Main类,我在其中执行AsyncTask,我想在AsyncTask完成之前停止主类的代码执行。在AsyncTask中,我从互联网上收集数据。我想收集数据,获取结果,并在onPostExecute()方法中通知。这是简化的代码:

public class MainClass extends Activity  {

    public class MyTask extends AsyncTask<String, Void, String> 
    {
        @Override
        protected String doInBackground(String... arg0) {

            //(...Some calcuations here)

            synchronized (self) {
                self.notify();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            textView.setText(result);
            //I would like to notify here, but it is not working
        }
    }

    private void callAsyncTask()
    {
        myTask = (MyTask) new MyTask().execute(someString, someOtherString);

        synchronized (self) 
        {
            try 
            {
                self.wait();
            } catch (InterruptedException e) { e.printStackTrace(); }
        }
    }

    //(...)Some code where I callAsyncTask()

}

我对使用wait()和notify()的理解是否正确?有人可以解释一下我在使用这些方法时应该注意什么?

1 个答案:

答案 0 :(得分:0)

要执行Asynctask时,只需在execute()之后使用get()

       MyTask mytask=new MyTask (); 
       mytask.execute("arg").get();
相关问题