线程在其工作完成时停止“他的兄弟们”

时间:2011-05-31 07:56:34

标签: java multithreading

给出以下

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MB5Returner extends Thread {

    private int startPoint;
    private int endPoint;

    public void run() {
        for (int i = startPoint; i < endPoint; i++) {
            try {
                String val = Words.allPossible.get(i);
                MessageDigest m;

                m = MessageDigest.getInstance("MD5");

                m.update(val.getBytes(), 0, val.length());
                String hashed = new BigInteger(1, m.digest()).toString(16);

            //  System.out.println("MD5 = " + hashed);
                checkMD5(hashed, val);

            } catch (NoSuchAlgorithmException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FoundMD5Exception e) {

            }
        }
    }

    private void checkMD5(String hashed, String val) throws FoundMD5Exception {
        if (hashed.equals(Main.hashedPassword)) {
            throw new FoundMD5Exception(hashed, val);
        }
    }

    public MB5Returner(int startPoint, int endPoint) {
        super();
        this.startPoint = startPoint;
        this.endPoint = endPoint;
    }

}

我做的很少像这样的线程。如果我的异常FoundMD5Exception被其中一个抓获,我怎么能停止所有这些?

2 个答案:

答案 0 :(得分:4)

最简单的解决方案可能是创建一个AtomicBoolean(称之为keepRunning或类似的东西)。将其作为对MB5Returner的构造函数的引用传递:

public class MB5Returner extends Thread {

    // ...
    private AtomicBoolean keepRunning;

    MB5Returner(AtomicBoolean keepRunning) {
        this.keepRunning = keepRunning;
    }

将for循环更改为

for (int i = startPoint; keepRunning.get() && i < endPoint; i++) {
                         ^^^^^^^^^^^^^^^^^

然后只需做

    // ...
} catch (FoundMD5Exception e) {
    keepRunning.set(false);
}

答案 1 :(得分:0)

您可以使用java线程中的中断机制。

在主线程中,保留对每个工作线程的引用。

像这样改变你的工人:

for (int i = startPoint; (i < endPoint && !Thread.currentThread().isInterrupted()); i++) {
    ...rest of code as usual
}

然后在主线程中,抓住FoundMD5Exception并为每个工作人员调用interrupt()