java如何安全的停止一个线程_java – 如何安全地停止多个线程?

博客讨论了在Java中如何安全地停止多个线程,特别是在用户点击'停止'按钮时。作者遇到的问题是,即使使用volatile标志中断线程,当涉及I/O操作时,线程似乎仍然继续运行。代码示例展示了线程启动和停止的方法,但遇到了在执行I/O操作后无法正确关闭的情况。问题集中在如何确保文件被正确处理并在停止线程时关闭。
摘要由CSDN通过智能技术生成

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

编辑

感谢大家的评论,只是为了跟帖子一起,我用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();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值