功能要求:
具體類:
Decrypt 測試類,用來啟動破解和日志線程
DecryptThread 破解線程類,用來生成測試的字符串,並暴力破解
LogThread 日志類,將輸出每次生成的字符串結果集,並且設置為守護線程,等DecryptThread線程運行結束,也將停止運行

package decrypt; import java.util.ArrayList; import java.util.List; import java.util.Random; public class Decrypt { // 生成長度為3的隨機字符串 private static String getRandomStr() { char []chs = new char[3]; Random rd = new Random(); for(int i=0;i<3;i++) { // 生成 [0,10) 的數 chs[i] =(char) (rd.nextInt(10)+'0'); } return new String(chs); } public static void main(String[] args) { String password = getRandomStr(); List<String> list = new ArrayList<String>(); DecryptThread dec = new DecryptThread(list, password); LogThread log = new LogThread(list); dec.start(); log.start(); } }

package decrypt; import java.util.List; import java.util.ArrayList; public class DecryptThread extends Thread { boolean ok = false; private List<String> list; private String password; public DecryptThread() {} public DecryptThread(List<String> list,String password) { this.list = list; this.password = password; } @Override public void run() { char []chs = new char[3]; String str=null; for(int i=0;i<=9;i++) { for(int j=0;j<=9;j++) { for(int k=0;k<=9;k++) { chs[0]=(char)(i+'0'); chs[1]=(char)(j+'0'); chs[2]=(char)(k+'0'); str = new String(chs); list.add(str); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } if(str.equals(password)) { System.out.printf("成功匹配到密碼,密碼是%s%n",str); ok=true; return ; } } } } } }

package decrypt; import java.util.List; import java.util.ArrayList; public class LogThread extends Thread{ private List<String> list; LogThread(){} LogThread(List<String> list) { this.list = list; // 日志線程設置為 守護線程 this.setDaemon(true); } @Override public void run() { while(true) { while (list.isEmpty()) { try { Thread.sleep(50); }catch(Exception e) { e.printStackTrace(); } } String password = list.remove(0); System.out.printf("生成的字符串是%s%n", password); } } }
可改進功能:
1.字符串長度增加,並且不僅有數字還有字母以及 特殊字符
2.可以將log日志得到的結果 輸出到文件,通過緩存來減少IO次數
3.可以將正確密碼 加密 存到 數據庫中,練習數據庫的操作
4.暫時還沒想到,嘿嘿