简体   繁体   English

Asyntask Android中的Thread.Sleep()

[英]Thread.Sleep() in Asyntask Android

Does doing Thread.Sleep(10) will have any side effects on performance of Applications? 做Thread.Sleep(10)会对应用程序的性能产生任何副作用吗?

To be precise will doing Thread.Sleep(100) inside DoinBackground() method will affect other Asyntasks in the Process? 准确地说,在DoinBackground()方法中执行Thread.Sleep(100)会影响进程中的其他Asyntasks吗?

If so is there a way we can cause a delay inside Asynctask so that other Tasks executing doesn't get affected? 如果是这样,我们可以在Asynctask内部导致延迟,以便其他执行的任务不受影响?

Thanks & Regards, 感谢和问候,

manjusg manjusg

YES it will affect the performance of your application. 是的,它会影响您的应用程序的性能。 AsyncTask executes serially, so this will delay start of other AsyncTask. AsyncTask以串行方式执行,因此这将延迟其他AsyncTask的启动。 But still if its necessary for your app to sleep in a AsyncTask without affecting other AsyncTask you can execute them in parallel. 但是,如果您的应用程序必须在AsyncTask中睡眠而不影响其他AsyncTask,您可以并行执行它们。 But this also has a drawback. 但这也有一个缺点。 This will consume more memory than the default one, so if you have more number of tasks to execute you may end up in OOM. 这将消耗比默认内存更多的内存,因此如果您要执行更多任务,则最终可能会在OOM中。 Below is how you can run your task in parallel 以下是如何并行运行任务的方法

yourAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);

hope it will help ;) 希望它会有所帮助;)

It depends on your android:targetSdkVersion="". 这取决于你的android:targetSdkVersion =“”。

http://developer.android.com/reference/android/os/AsyncTask.html http://developer.android.com/reference/android/os/AsyncTask.html

When first introduced, AsyncTasks were executed serially on a single background thread. 首次引入时,AsyncTasks在单个后台线程上串行执行。 Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. 从DONUT开始,这被改为一个线程池,允许多个任务并行运行。 Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution. 从HONEYCOMB开始,任务在单个线程上执行,以避免由并行执行引起的常见应用程序错误。

If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR. 如果您真的想要并行执行,可以使用THREAD_POOL_EXECUTOR调用executeOnExecutor(java.util.concurrent.Executor,Object [])。

The safest way is to execute them parallel with an Executor as mentioned above, but this requires the minimum SDK of 11. An alternative solution is to check the current SDK and use executor only when available: 最安全的方法是如上所述与Executor并行执行它们,但这需要最小的SDK为11.另一种解决方案是检查当前的SDK并仅在可用时使用executor:

if (Build.VERSION.SDK_INT >= 11) {
     // use executor to achieve parallel execution
     asy.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else { 
     // this way they will execute parallel by default
     asy.execute();
}

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

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