Android 线程 - 延迟重复线程组几次
我将实现一个从 Android 设备收集数据的应用程序。
这是我现在所拥有的:
- 带有按钮的主要活动运行
- 按钮启动记录器
- 记录器有4个资源 可运行
- Gps资源
- 图像资源
- 音频资源
- 陀螺仪资源
- 在Recorder中,有一个for循环(例如
i <3
),它运行线程包一些延迟 (i * 5000
)
我应该如何创建该线程,以便所有线程同时启动 (i=0
),然后在 5 秒后再次启动 (i=1
) 并在接下来的 5 秒后再次 (i=2
) ?
接下来的事情:
每个资源都使用 getData()
方法返回一些数据 - 简化它 - 带有随机字符的字符串。如何在Recorder中通知队列中的所有线程都已完成并从资源中收集所有数据?
最后一件事:
我必须能够在创建所有队列后停止执行所有线程。示例:
我们有第 7 秒,第二个队列正在运行,用户单击按钮停止。正在运行的线程的队列即将完成,但下一个队列将不会启动,只是 Recodred 必须忘记它们。
我尽量写得简单一些,相信你们能理解我的意思。
感谢您的任何建议!
I am going to implement an application that is gathering data from Android device.
Here is what I have right now:
- Main activity with a button Run
- Button starts a Recorder
- Recorder has 4 Resources that are Runnable
- GpsResource
- ImageResource
- AudioResource
- GyroscopeResource
- In Recorder there is a for loop (for example
i < 3
) that runs pack of threads with some delay (i * 5000
)
How should I create that threads so all of them will start simultaneously (i=0
), then after 5 seconds start again (i=1
) and after next 5 seconds again (i=2
) ?
Next thing:
Every resource returns some data with getData()
method - simplify it - string with random characters. How to notify in Recorder that all threads in queue are completed and gather all data from resources ?
The last thing:
I have to be able after creating all that queues to stop executing all threads. Example:
We have a 7th second, 2nd queue is running now and user clicks a button Stop. Queue with running threads is going to complete, but next queues will not start, just Recodred has to forget about them.
I tried to write as simple as possible, I believe that you guys understand me.
Thanks for any advices !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有一个想法可以解决至少一部分问题:
一起启动资源并等待它们完成:
采用
CompletionService
:Resource
应该如下所示:不从完成服务中获取数据:
请注意,这更多是伪代码,未经过实际测试:)
并且仍然存在悬而未决的问题,如果某些资源执行时间超过 5 秒,您会做什么。另一种是每 5 秒安排一次相同的操作。
Here is an idea to solve at least one part of the question:
To start resources together and wait for them to complete:
Take a
CompletionService
:Resource
should look something like this:Not to get the data back from the completion service:
Please note that this is more of pseudo-code, not actually tested :)
And there are still open questions what would you do if some resource takes more than 5 seconds to execute. Another one is to schedule the same operations every 5 seconds.