我在用户点击用户界面上的“停止”按钮时尝试安全地停止多个线程时创建了一个小例子(如下).然而,似乎在这次尝试之后,线程似乎仍在运行.你能指点我正确的方向吗?
编辑
感谢大家的评论,只是为了跟帖子一起,我用volatile boolean标志修改了下面的代码,它似乎工作正常,直到我做一些I / O操作.
如果我添加I / O操作,即使调用fstream.close然后调用stop函数来打开boolean标志,线程似乎也在运行…(描述程序以仔细检查线程是否仍在运行) .
为了处理打开的文件,我还需要做任何其他事情,并最终停止线程吗?
再次感谢.
固定和工作代码.
class MultiThreadExample implements Runnable {
private static final MultiThreadExample threadObj = new MultiThreadExample();
ArrayList threadList = new ArrayList();
public static MultiThreadExample getInstance() {
return threadObj;
}
public void tester() {
File file = new File("data/");
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
Thread thread = new Thread(new ThreadedCrawler(), files[i].toString());
thread.start();
threadList.add(thread);
}
}
public void run() {
try {
ProgramTester.getInstance().doSomething();
}
finally {
do other stuff
}
}
public synchronized void stop() throws IOException {
for (Thread threads : threadList)
threads.interrupt();
}
public void doSomething() {
FileInputStream fstream = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String inLine;
while (((inLine = br.readLine()) != null) && !Thread.currentThread().isInterrupted()) {
do something...
for()...
....
}
}
}
public class GuiExample extends JFrame {
....
public void mousePressed(MouseEvent e) {
try {
MultiThreadExample.getInstance().stop();
}
catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}