gpt4 book ai didi

java - 如何安全地停止多个线程?

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:54:34 25 4
gpt4 key购买 nike

我创建了一个小示例(如下),试图在用户单击用户界面上的“停止”按钮时安全地停止多个线程。然而,在这次尝试之后,线程似乎仍在运行。你能给我指出正确的方向吗?

编辑

感谢大家的评论,为了配合帖子,我用 volatile boolean 标志修改了下面的代码,在我进行一些 I/O 操作之前它似乎工作正常。
如果我添加 I/O 操作,线程似乎正在运行,即使调用 fstream.close 然后调用停止函数打开 boolean 标志...(分析程序以仔细检查线程是否仍在运行) .为了处理打开的文件并最终停止线程,我还需要做任何其他事情吗?
再次感谢。

固定的工作代码。

class MultiThreadExample implements Runnable {
private static final MultiThreadExample threadObj = new MultiThreadExample();
ArrayList<Thread> threadList = new ArrayList<Thread>();

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();
}
}
}

最佳答案

interrupt() 不会停止线程(请参阅 API)。处理此问题的首选方法是让您的 run() 方法定期检查标志并在设置标志时退出(当然,您在要终止线程时设置标志)。

stop() 终止线程,但它已被弃用很长时间(有充分的理由)。

同样的问题 here

更新

由于您在 doSomething() 之外检查标志,它不会在方法完成之前退出,因此长时间运行的任务(如文件 io)将继续。

将检查移动到 br.readLine() 的循环中,正如其他人所建议的那样,在这里使用 interrupt()/isInterrupted() 可能更好,因为它还将停止在 io 上阻塞的线程。

关于java - 如何安全地停止多个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9104990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com