我在arraylist中存储了一堆线程对象。我希望能够随机启动这些线程。同一线程可以多次启动。在启动线程对象之前,请检查线程是否处于活动状态,以及它们是否处于NEW或TERMINATED状态。此限制是因为,我不想打扰“忙碌”线程。现在,对于NEW线程,这可以正常工作。但是对于TERMINATED线程,我得到了一个例外。

当线程结束时,它不应该回到“新的”状态吗?还是线程是“一次性的”-就像一次使用完成?

有帮助吗?

解决方案

As it says in the documentation for Thread.start(), "It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution."

It is better for you to keep hold of Runnable instances and implement your own logic for keeping track of when the execution of each one of them finishes. Using an Executor is probably the simplest way to run the Runnables.

其他提示

You should probably be using the awesome stuff provided in java.util.concurrent. Based on your description, ThreadPoolExecutor sounds like a good thing to check out.

This is the way I did it

class GarbageDisposalThread extends Thread {
public void start() {
   try {
      super.start();
   } catch( IllegalThreadStateException e ) {
      this.arrayList.remove(this);
      this.arrayList.add( new GarbageDisposalThread( this.arrayList ));
   }
}
private GarbageDisposalThread() {
}
public GarbageDisposalThread( ArrayList<Whatever> arrayList ) {
   this.arrayList = arrayList;
   this.start();
}
public void run() {
   // whatever the code
}
private ArrayList<Whatever> arrayList = null;
}

that's it! you can change the code according to your needs :P

Java threads cannot be restarted.

From the javadoc:

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

See the Thread.start() javadoc for more information.

There are other ways to accomplish what you are trying to do. For example, you could use new Threads that continue the work that was done in the Thread that has finished execution. You may also want to investigate the java.util.concurrent package.

From another post...

You could use ThreadPoolExecutor, which would allow you to pass in tasks and let the service assign a thread to a task. When the task is finished, the thread goes idle until it gets the next task.

So, you don't restart a thread, but you would redo/resume a task.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top