Android,线程使用

Android,线程使用,android,multithreading,exception,Android,Multithreading,Exception,当加速度计数据超过我确定的阈值时,我的程序正在向web服务器发送数据。因此,我使用线程机制发送操作: if( threshold is exceeded ) thread_send .start(); 但这种用法会导致“线程已使用”错误。因此,我使用了一种我认为不好的方法,如下所示: if( threshold is exceeded ) { thread_send = new Thread(this); send_thread.start(); } 每转一圈都会产生

当加速度计数据超过我确定的阈值时,我的程序正在向web服务器发送数据。因此,我使用线程机制发送操作:

if( threshold is exceeded )
    thread_send .start();
但这种用法会导致“线程已使用”错误。因此,我使用了一种我认为不好的方法,如下所示:

if( threshold is exceeded ) {
    thread_send = new Thread(this);
    send_thread.start();
}
每转一圈都会产生新的线程。这种用法会导致负面结果吗?(例如,内存问题或性能问题等)

你有什么建议

编辑:

我的程序应该经常向web服务器发送数据。最重要的是工作正常。因此,只要程序不能突然停止,缓慢的工作是允许的

根据您的建议,我使用了Executor服务:

ExecutorService threadExecutor = Executors.newSingleThreadExecutor();

........    

if( threshold is exceeded ) {
   threadExecutor.execute(this);
}
但出现了错误:ReceijtedExecutionException。。


我能做什么?

第二个代码看起来是正确的,但如果有太多线程并行运行,它可能会减慢速度。根据应用程序的不同,让线程在队列中一次运行一个线程可能比较合适。

一个想法是创建一个运行线程的类似单例的服务,这样,如果一个线程没有运行,那么它会启动一个线程,否则它会忽略它


如果您希望同时运行多个,那么您所拥有的是正确的。请记住,每个新线程只能运行一次线程()。例如,如果您可以等待一段时间,那么您可以将数据保存在内存中,并在应用程序完成后一次性发送所有数据。如果您几乎连续发送数据,那么执行多个工作的单个线程或由执行者创建的线程池(例如由
Executors.newXXX
创建的线程池)可能会更好。