简体   繁体   English

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

[英]Multithreading with AsyncTask(): using wait() and notify()

I am having hard time to understand how multitasking works in Java.我很难理解 Java 中的多任务处理是如何工作的。 I read some articles here on SO but still have problems.我在这里阅读了一些关于 SO 的文章,但仍有问题。

I have my Main class, in which I execute AsyncTask, and I would like to stop code execution of main class until the AsyncTask is finished.我有我的 Main 类,我在其中执行 AsyncTask,我想停止主类的代码执行,直到 AsyncTask 完成。 In AsyncTask I gather data from internet.在 AsyncTask 中,我从互联网上收集数据。 I would like to gather data, get the result, and notify in onPostExecute() method.我想收集数据,获取结果,并在 onPostExecute() 方法中通知。 Here is simplified code:这是简化的代码:

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

}

Is my understanding of using wait() and notify() correct?我对使用 wait() 和 notify() 的理解正确吗? Can someone explain me what should I be aware of while using those methods?有人可以解释我在使用这些方法时应该注意什么吗?

just use get() after execute() when you wanna execute the Asynctask当您想执行 Asynctask 时,只需在 execute() 之后使用 get()

       MyTask mytask=new MyTask (); 
       mytask.execute("arg").get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM