giving the following
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.getByt开发者_如何学Pythones(), 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;
}
}
I'm making few of threads like this one. How can I stop all of them if my exception FoundMD5Exception
was catched in one of them?
The simplest solution is probably to create an AtomicBoolean
(call it keepRunning
or something similar). Pass it as a reference to the constructor of MB5Returner
:
public class MB5Returner extends Thread {
// ...
private AtomicBoolean keepRunning;
MB5Returner(AtomicBoolean keepRunning) {
this.keepRunning = keepRunning;
}
Change the for-loop into
for (int i = startPoint; keepRunning.get() && i < endPoint; i++) {
^^^^^^^^^^^^^^^^^
Then simply do
// ...
} catch (FoundMD5Exception e) {
keepRunning.set(false);
}
There is an interruption mechanism in java threads that you could use.
In your main thread, keep a reference to each worker thread.
Alter your workers like this:
for (int i = startPoint; (i < endPoint && !Thread.currentThread().isInterrupted()); i++) {
...rest of code as usual
}
Then in your main thread, catch FoundMD5Exception
and call interrupt()
on each worker.
精彩评论