开发者

Reusing a thread

I am trying to get my head around threads, and after attempting many times to get my head around it, I am stuck on this point.

I want to get some remote data from a server. I create a thread to handle this operation. I understand this. But if I want to get some more remote data, I end up creating a new thread. This seems a bit daft, as shouldnt I be able to re-use the existing thread.

After trying to understand how I could do this, I think the answer lies in sending messages to the thread? But I am totally baffled by this.

Here is a example of where I need to get lo开发者_运维百科ts of remote data based on a variable within a for statement:

for(int i = 0; i < jsonarray.length(); i++){
   String httpUserId = jsonarray.getJSONObject(i).getString("user_id");
   //Get Sub Comments
   userId = httpUserId
   Thread t = new Thread(null, getUserPrefs, "getUserPrefs");
   t.start();
}

As you can see in the example, I need to call the remote server lots of times, but instead of creating a new thread each time, shouldnt I be able to reuse one thread that I can create earlier?

If anyone can help I would be most grateful :)


There is the ThreadPoolExecutor in Android. An example of this in action can be found here: http://code.google.com/p/shelves/source/browse/trunk/Shelves/src/org/curiouscreature/android/shelves/util/UserTask.java

You can use this example and modify it to match your needs


Application servers tend to (re)use pools of threads. This requires logic to be able communicate between some controlling thread and the worker threads. The controller has got to keep track of the threads that are currently available, have the ability to tell a thread to do some work and wait for each worker to finish. The worker thread needs to be able to find out about the work it has to do and to communicate the fact that it has finished.

So to implement this you need to have some inter-thread communication techniques. This is all not completely trivial to write - there tend to be lots of race conditions to consider. Clearly the App Server vendors see advantages in using these techniques, but they are targetting quite high performance requirements.

You are presumably concerned about the costs of creating and destroying a Thread. I'm doubtful that you need to be concerned about this relative to the costs in making network calls and parsing JSON objects.

Java has an Executor framework that addresses some of the complexity. I'm afraid I don't know Android so I don't know whether you have this available to you, but if not you could maybe study implementations of this framework?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜