Android Thread Pool to manage multiple bluetooth handeling threads?

别来无恙 提交于 2019-12-08 01:41:13

问题


So I have my Android Bluetooth application that has it's host and clients. The problem is, because I am making multiple connections, I need a thread to handle each connection. That's all milk'n'cookies, so I thought I'd stick all the threads in an array. A little research says a better method to doing this is using a Thread Pool, but I can't seem to get my head around how that works. Also, is it actually even possible to hold threads in an array?


回答1:


A thread pool is built around the idea that, since creating threads over and over again is time-consuming, we should try to recycle them as much as possible. Thus, a thread pool is a collection of threads that execute jobs, but are not destroyed when they finish a job, but instead "return to the pool" and either take another job or sit idle if there is nothing to do.

Usually the underlying implementation is a thread-safe queue in which the programmer puts jobs and a bunch of threads managed by the implementation keep polling (I'm not implying busy-spinning necessarily) the queue for work.

In Java the thread pool is represented by the ExecutorService class which can be:

  • fixed - create a thread pool with a fixed number of threads
  • cached - dynamically creates and destroys threads as needed
  • single - a pool with a single thread

Note that, since thread pool threads operate in the manner described above (i.e. are recycled), in the case of a fixed thread pool it is not recommended to have jobs that do blocking I/O operations, since the threads taking those jobs will be effectively removed from the pool until they finish the job and thus you may have deadlocks.

As for the array of threads, it's as simple as creating any object array:

Thread[] threads = new Thread[10]; // array of 10 threads


来源:https://stackoverflow.com/questions/9707395/android-thread-pool-to-manage-multiple-bluetooth-handeling-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!