該類主要完成查找密碼,完成密碼匹配。
package testthread;
import java.util.ArrayList;
import java.util.List;
public class GetPasswd extends Thread{
private List<String> passwds;
private String passwd;
public GetPasswd(List<String> passwds,String passwd) {
this.passwds = passwds;
this.passwd = passwd;
}
public void getPasswd(String passwd) {
char ch[] = new char[3];
for (int i = 48; i < 122; i++) {
for (int j = 48; j < 122; j++) {
for (int k = 48; k < 122; k++) {
ch[0] = (char)i;
ch[1] = (char)j;
ch[2] = (char)k;
String str = new String(ch);
passwds.add(str);
if(str.equals(passwd)) {
System.out.println("破解成功,密碼是:" + str);
return ;
//return後面也可以不帶參數,不帶參數就是返回空,其實主要目的就是用於想中斷函數執行,返回調用函數處。
//爲啥不能用break,因爲break只終止最內層的循環
}
}
}
}
}
public void run() {
getPasswd(passwd);
}
}
該類主要完成log打印,完成守護線程。
package testthread;
import java.util.List;
public class TestDaemon extends Thread{
private List<String> slist;
public TestDaemon(List<String> s) {
this.slist = s;
this.setDaemon(true);
}
public void run() {
while(slist.isEmpty()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
while(true) {
String s = slist.remove(0);
System.out.println("窮舉法本次生成的密碼是:" +s);
}
}
}
以下是測試類
package testthread;
import java.util.ArrayList;
import java.util.List;
public class TestGetPasswd {
public static void main(String[] args) {
String a = generateRandomString(3);
System.out.println("產生的原始密碼爲:"+a);
List<String> s = new ArrayList<>();
GetPasswd gp = new GetPasswd(s, a);
gp.start();
TestDaemon td = new TestDaemon(s);
td.start();
}
public static String generateRandomString(int len) {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < len; i++) {
while(true) {
char ch = (char)(Math.random()*'z');
if(Character.isDigit(ch)||Character.isLetter(ch)) {
sb.append(ch);
break;
}
}
}
return sb.toString();
}
}