[英]Java Multithread stopping all other threads immediately
我有以下代碼:
public class BruteForceThread implements Callable<String> {
private static volatile boolean stopped = false;
public String call() {
String password = this.getNextPassword();
while (!stopped) {
System.out.println(numberOfThreat + ": " + password);
synchronized(this) {
try {
if (this.testPassword(password)) {
stopped = true;
return password;
}
} catch (IOException e) {
e.printStackTrace();
}
}
password = this.getNextPassword();
}
return "";
}
}
主班:
public static void main(String[] args) throws IOException {
int numberOfThreads = 2;
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
CompletionService<String> pool = new ExecutorCompletionService<String>(executor);
for (int i = 1; i < numberOfThreads + 1; i++) {
Callable<String> bruteForce = new BruteForceThread(...);
pool.submit(bruteForce);
}
executor.shutdown();
for(int i = 0; i < numberOfThreads; i++){
try {
String result = pool.take().get();
if (result != "") {
System.out.println("Your password: " + result);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
executor = null;
}
輸出:...
1: aa <- here first thread found a password
2: Fa <- second thread is continue
2: Fb
2: Fc
... many more ...
2: IZ
Your password: aa
如果一個線程找到密碼並將其設置為true,則另一個線程不會立即停止。 為什么?
將有等待寫入控制台的線程。 這意味着某些線程或所有線程都可能在檢查停止狀態和輸出到屏幕之間。
順便說一句,除非您以高等待時間入侵網站,否則您可能會發現破解密碼僅使用與CPU數量相同的線程來完成。 更多線程可能會增加開銷並減慢它的速度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.