我想通过使用布尔值字段来停止线程。我已经实现了一些代码来做到这一点,如下所示:
我的线程类是这样的:
public class ParserThread implements Runnable {
private volatile boolean stopped = false;
public void stopTheThread() {
stopped = true;
}
:
:
}下面是从函数start()启动10个线程的主线程
public class Main() {
Thread [] threads;
public void start() {
for(int i = 0; i < 10; i++) {
threads[i] = new Thread(new ParserThread());
}
}
public void stop() {
// code to stop all the threads
}
}现在我想调用ParserThread的stop方法来设置"stopped = true“来停止线程。我希望这件事是为所有的10个线程。
如何调用stop方法。我希望它在主类的stopAllThreads()方法中完成。
发布于 2009-10-23 21:44:05
这里是使用ExecutorService的另一种替代方法。与直接操作线程相比,它需要的代码更少,并且提供了两种停止工作线程的替代方法。它还允许您潜在地捕获每个工作项的结果(如果您使用Callable实例而不是Runnables)。即使您不希望捕获显式返回值,它也允许您轻松地将任何异常编组回主线程。
// Array of Runnables that we wish to process.
ParserThread[] parserThreads = ...
// Create executor service containing as many threads as there are Runnables.
// (Could potentially have less threads and let some work items be processed
// sequentially.)
ExecutorService execService = Executors.newFixedThreadPool(parserThreads.length);
// Submit each work item. Could potentially store a reference to the result here
// to capture exceptions.
for (ParserThread runnable : parserThreads) {
execService.submit(runnable);
}然后,要关闭所有线程,您可以调用:
executorService.shutDown(); // Initiates an orderly shut-down of the service...。或
executorService.shutDownNow(); // Stops all tasks, interrupting waiting tasks.发布于 2009-10-23 21:35:57
看一看Executor框架。如果你使用ExecutorService,你可以提交你所有的作品作为Runnables。executor框架将跟踪所有这些线程,并且所有托管线程将通过shutdownNow()方法接收关闭请求(interupt)。
你的线程必须正确地处理中断。有关详细信息,请参阅this article。
使用Executor框架管理线程集、收集结果、处理异常等通常会更容易。
发布于 2009-10-23 21:31:03
您必须保持对ParserThread对象本身的控制:
public class Main() {
ParserThread[] parserthreads = new ParserThread[10];
public void start() {
for(int i = 0; i < 10; i++) {
parserthreads[i] = new ParserThread();
new Thread(parserthreads[i]).start();
}
}
public void stop() {
for (int i = 0; i < 10; i++) {
parserthreads[i].stopTheThread();
}
}
}如果你需要线程对象本身(例如,对它们进行join() ),要么单独跟踪它们,要么让ParserThread继承线程:
public class ParserThread extends Thread {
private volatile boolean stopped = false;
public void stopTheThread() {
stopped = true;
}
}此外,正如其他许多人指出的那样,stopTheThread()无用地复制了类Thread上的interrupt方法,因此您最好的选择是:
public class Main() {
Thread[] parserthreads = new Thread[10];
public void start() {
for(int i = 0; i < 10; i++) {
parserthreads[i] = new Thread(new ParserThread());
parserthreads[i].start();
}
}
public void stop() {
for (int i = 0; i < 10; i++) {
parserthreads[i].interrupt();
}
}
}然后在ParserThread中,尽可能频繁地调用if (Thread.currentThread().isInterrupted())。
https://stackoverflow.com/questions/1613435
复制相似问题