简体   繁体   English

Android - 如何并行运行多个线程

[英]Android - How to Run Multiple Threads in Parallel

I am developing an android application that synchronizes the user's emails using Gmail API. 我正在开发一个Android应用程序,使用Gmail API同步用户的电子邮件。

To do so i have implemented two services where the first is for downloading the Unread Emails and the second is for downloading Read Emails. 为此,我实施了两项服务,其中第一项是下载未读电子邮件,第二项是下载阅读电子邮件。 Each service implements the Runnable interface and the code for retrieving the emails and storing them in the database is handled using a thread inside the Run() method. 每个服务都实现了Runnable接口,并且使用Run()方法内的线程处理用于检索电子邮件并将它们存储在数据库中的代码。

Everything works fine the only problem i have is that when the Thread responsible for downloading the Read Emails is running (which takes longer than the other) the second Thread (Sync unread emails) is blocked until the first one is completed. 一切正常我唯一的问题是,当负责下载读取电子邮件的线程正在运行时(比另一个更长),第二个线程(同步未读电子邮件)被阻止,直到第一个线程完成。

I would like to know if there is anyway that i can prioritize the second Thread over the first one so whenever the first one is running and the second thread have to run, the code should put the second thread on hold until the first one (Unread emails) complete running and then resume the thread on hold. 我想知道是否有任何方式我可以优先考虑第二个线程超过第一个线程,所以每当第一个线程运行并且第二个线程必须运行时,代码应该保持第二个线程直到第一个线程(未读)电子邮件)完成运行,然后恢复保持的线程。

Regards. 问候。

If you would like to create a second service that runs for just a short time i would suggest you to study the AsyncTask, but if you are looking to create a service that runs constantly you would need to use the java.util.concurrent API(Executor, ThreadpoolExecutor). 如果你想创建一个运行时间很短的第二个服务,我建议你学习AsyncTask,但如果你想创建一个不断运行的服务,你需要使用java.util.concurrent API(执行者,ThreadpoolExecutor)。 Wish i helped, but with a few readings you can pick up more knowledge about multithreaded applicarions. 希望我能帮到你,但是通过一些阅读,你可以获得更多关于多线程应用的知识。 Tell me if you need more help! 如果您需要更多帮助,请告诉我!

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

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