【问题标题】:How can I properly clean unused threads?如何正确清理未使用的线程?
【发布时间】:2011-06-22 00:08:36
【问题描述】:

我有一个监听传入消息的客户端软件(在 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:现在每次有消息时都会创建此线程。我怎样才能只创建一个线程并一次又一次地使用它?有什么想法吗?

【问题讨论】:

    标签: android multithreading user-interface


    【解决方案1】:
    1. 创建一个新的Thread
    2. 在线程的run() 方法中创建一个新的Handler
    3. 当你想在目标线程上做某事时,使用 Handler 的post() 方法。

    您可以在主线程上创建一个处理程序来回发更新 GUI 的操作。

    还可以考虑使用AsyncTask<>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多