有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

异步任务中的java Volatile和Synchronized

在AsyncTask的内部实现中(在Android SDK中)heresDefaultExecutorvolatile关键字声明,并且SerialExecutor中的execute()方法用synchronized关键字声明

  1. 现在,由于AsyncTask只能从UI线程执行,而且如果 我们执行AsyncTask的一个实例,我们不能执行相同的实例 除非上一个实例已完成执行,否则请再次执行。 那么,这里为什么会出现多线程的情况呢
  2. 为什么SerialExecutor有一个ArrayDeque?因为我们曾经 只能有一个任务。如果我们创建一个AsyncTask的新实例, 那么我们会不会得到一个新的ArrayDeque实例,它同样只有 要处理的任务是什么
  3. ThreadPoolExecutor的情况也是如此。为什么是线程池 对于AsyncTask的特定实例,我们可以 只有一项任务?一根线就够了

共 (1) 个答案

  1. # 1 楼答案

    we cant excute the same instance again unless the previous instance has finished executing. So how come there can be cases of multiple threads here?

    例如,有主UI线程和执行器线程

    Why the SerialExecutor has an ArrayDeque? Because at a time we can have only one task. If we create a new instance of AsyncTask, then wont we get a new instance of ArrayDeque,again which has only one Task to deal with?

    不是只有一项任务。串行执行器一次只能执行一个任务,但您可以在主线程中将多个任务排队,然后在执行器线程中逐个执行这些任务

    除了串行执行器之外,还有其他执行器,比如后面提到的线程池执行器

    Same is the case with ThreadPoolExecutor. Why are the thread pools required when for a particular instance of AsyncTask,we can have only one Task? One thread is suffice for that.

    你一次只做一项任务的前提是不正确的。线程池执行器对于在不同线程中同时运行多个异步任务非常有用

    How does queuing of taks and multiple tasks come into picture? Suppose i make an instance of AsyncTask and execute it 5 times. Then if one is running, other 4 wont start. SO how can i get multiple tasks in any case?

    只能执行一次AsyncTask的一个实例。但是您可以发布多个不同的AsyncTask实例来执行。请注意,这样的发布操作(execute()等等)是异步的,在异步任务完成之前返回,您可以在UI线程中运行其他代码,包括发布新的异步任务以执行

    对于并行执行,只需使用executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, ...)

    Is it also true that since SerialExecutor is static, so only one instance of it will be used across all the AsyncTask instances and so a queue is required?

    是的,你的应用程序中只有一个串行执行器,它在所有异步任务之间共享