如何正确清理未使用的线程?

时间:2011-06-21 15:57:22

标签: android multithreading user-interface

我有一个客户端软件(在Android上),可以监听传入的消息。消息在while循环中接收,等待消息到来。找到消息后,它会更新GUI。 [因为在Android中,GUI无法直接更新]调用线程来执行此操作。我的问题是,如果有很多消息,结果会有很多线程!它创造了一个笨拙的局面。我的抽象代码是,

My_Client()
{
  send_text_function() // My question is not about it
  in_a_thread_Call_receive_from_others_function() [see 1]
}

receiving_funtion() // [this function is mentioned above as (see 1), called in a thread]
{
  while( waiting for new message)
  {
    >>A new message found >> create a thread to update the GUI.  // << Here is my question. see 2
  //android.os.Handler.thread type thread!
  } 
}

标签2:现在每次有消息时都会创建此线程。我怎样才能创建一个线程并一次又一次地使用它?有什么想法吗?

1 个答案:

答案 0 :(得分:1)

  1. 制作新的Thread
  2. 在Thread的run()方法中创建一个新的Handler
  3. 如果要在目标线程上执行某些操作,请使用处理程序的post()方法。
  4. 您可以在主线程上创建一个Handler来回发更新GUI的操作。

    另请考虑使用AsyncTask<>