[英]Why do I get this error in my TimerTask?
08-17 18:26:44.540: E/AndroidRuntime(2405): FATAL EXCEPTION: Scheduler
08-17 18:26:44.540: E/AndroidRuntime(2405): java.lang.IllegalThreadStateException: Thread already started.
08-17 18:26:44.540: E/AndroidRuntime(2405): at java.lang.Thread.start(Thread.java:1045)
08-17 18:26:44.540: E/AndroidRuntime(2405): at com.example.simpledownloader.scheduler.Scheduler.run(Scheduler.java:21)
08-17 18:26:44.540: E/AndroidRuntime(2405): at java.util.Timer$TimerImpl.run(Timer.java:284)
So, I have a TimerTask
which checks all the pending downloads by brute forcing. 因此,我有一个TimerTask
,它通过蛮力检查所有未完成的下载。
Downloads are all Thread
stored in a Vector
. 下载都是Thread
存储在一个Vector
。 As soon as the TimerTask
sees the a thread is ready, it calls start()
on it. 一旦TimerTask
看到线程已准备就绪,它将在其上调用start()
。 here is the code: 这是代码:
Code: 码:
package com.example.simpledownloader.scheduler;
import java.util.TimerTask;
import android.util.Log;
import com.example.simpledownloader.sharable.Sharable;
import com.example.simpledownloader.task.Task;
public class Scheduler extends TimerTask {
//------------------------------------------------------------------------------
@Override
public void run() {
if(Sharable.getShouldLook()){ // Should we look for pending tasks ?
for(Task each: Sharable.downloads){ // Yes, then loop
if(each.isAlive()==false){ // Thread is not running ?
Log.v("SCHEDULER", "NOT RUNNING");
if(each.getReadiness() == true){ // Is it ready ?
each.start(); // Start !
break; // stop looping
}
}
}
}
}
//------------------------------------------------------------------------------
}
Why do I keep getting that error ? 为什么我不断收到该错误?
The Timer
is set as such: Timer
设置如下:
Sharable.schedulerTimer.scheduleAtFixedRate(Sharable.schedulerTask, 1000, 1000); // start scheduler
You're checking before you start the thread if isAlive()
returns false. 如果isAlive()
返回false,则在启动线程之前进行检查。 There are two ways that this could not be adequate to prevent you from getting the IllegalThreadStateException
: 有两种方法不足以阻止您获得IllegalThreadStateException
:
Some other thread is starting the download thread between the call to isAlive()
and the call to start()
, or 另一个线程正在启动对isAlive()
的调用与对start()
的调用之间的下载线程,或者
The download thread is terminating without being removed from your Sharable.downloads
collection. 下载线程将终止,而不会从Sharable.downloads
集合中删除。
My suspicion is that the latter is more likely, so that's where I'd start looking. 我怀疑后者的可能性更大,所以这就是我开始寻找的地方。 Alternatively, if you want to keep your threads in the downloads collection after they've finished, you may want to try each.getState() == Thread.State.NEW
instead of each.isAlive() == false
. 另外,如果您希望在完成下载后将线程保留在下载集合中,则可能需要尝试each.getState() == Thread.State.NEW
而不是each.isAlive() == false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.