Java 如何使用多线程加速代码?
我用Java创建了一个密码破解程序,可以破解文本文件列表中的密码。然后,它生成一个包含以下成对内容的词典:经过哈希处理的单词和原始单词。我正在寻找一种加速程序的方法,让它读取文件中的所有单词,然后使用多线程生成哈希。如何将单词列表分解成四个单独的分区,然后在createDictionary方法中让多个线程对其进行操作?以下是我到目前为止的情况:Java 如何使用多线程加速代码?,java,multithreading,Java,Multithreading,我用Java创建了一个密码破解程序,可以破解文本文件列表中的密码。然后,它生成一个包含以下成对内容的词典:经过哈希处理的单词和原始单词。我正在寻找一种加速程序的方法,让它读取文件中的所有单词,然后使用多线程生成哈希。如何将单词列表分解成四个单独的分区,然后在createDictionary方法中让多个线程对其进行操作?以下是我到目前为止的情况: public class Main { private static final String FNAME = "words.txt&
public class Main {
private static final String FNAME = "words.txt";
private final static String PASSWDFNAME = "passwd.txt";
private static Map<String, String> dictionary = new HashMap<>();
public static void main(String[] args) {
// Create dictionary of plain / hashed passwords from list of words
System.out.println("Generating dictionary ...");
long start = System.currentTimeMillis();
createDictionary(FNAME);
System.out.println("Generated " + dictionary.size() + " hashed passwords in dictionary");
long stop = System.currentTimeMillis();
System.out.println("Elapsed time: " + (stop - start) + " milliseconds");
// Read password file, hash plaintext passwords and lookup in dictionary
System.out.println("\nCracking password file ...");
start = System.currentTimeMillis();
crackPasswords(PASSWDFNAME);
stop = System.currentTimeMillis();
System.out.println("Elapsed time: " + (stop - start) + " milliseconds");
}
private static void createDictionary(String fname) {
// Read in list of words
List<String> words = new ArrayList<>();
try (Scanner input = new Scanner(new File(fname));) {
while (input.hasNext()) {
String s = input.nextLine();
if (s != null && s.length() >= 4) {
words.add(s);
}
}
} catch (FileNotFoundException e) {
System.out.println("File " + FNAME + " not found");
e.printStackTrace();
System.exit(-1);
}
// Generate dictionary from word list
for (String word : words) {
generateHashes(word);
}
}
private static void crackPasswords(String fname) {
File pfile = new File(fname);
try (Scanner input = new Scanner(pfile);) {
while (input.hasNext()) {
String s = input.nextLine();
String[] t = s.split(",");
String userid = t[0];
String hashedPassword = t[1];
String password = dictionary.get(hashedPassword);
if (password != null) {
System.out.println("CRACKED - user: "+userid+" has password: "+password);
}
}
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
System.exit(-1);
}
}
private static void generateHashes(String word) {
// Convert word to lower case, generate hash, store dictionary entry
String s = word.toLowerCase();
String hashedStr = HashUtils.hashPassword(s);
dictionary.put(hashedStr, s);
// Capitalize word, generate hash, store dictionary entry
s = s.substring(0, 1).toUpperCase() + s.substring(1);
hashedStr = HashUtils.hashPassword(s);
dictionary.put(hashedStr, s);
}
}
公共类主{
私有静态最终字符串FNAME=“words.txt”;
私有最终静态字符串PASSWDFNAME=“passwd.txt”;
私有静态映射字典=新HashMap();
公共静态void main(字符串[]args){
//从单词列表创建普通/哈希密码字典
System.out.println(“生成字典…”);
长启动=System.currentTimeMillis();
createDictionary(FNAME);
System.out.println(“生成的”+字典中的字典.size()+“哈希密码”);
长时间停止=System.currentTimeMillis();
System.out.println(“运行时间:”+(停止-启动)+“毫秒”);
//读取密码文件,散列明文密码并在字典中查找
System.out.println(“\n正在备份密码文件…”);
start=System.currentTimeMillis();
密码(PASSWDFNAME);
停止=System.currentTimeMillis();
System.out.println(“运行时间:”+(停止-启动)+“毫秒”);
}
私有静态void createDictionary(字符串fname){
//读入单词表
List words=new ArrayList();
尝试(扫描仪输入=新扫描仪(新文件(fname));){
while(input.hasNext()){
字符串s=input.nextLine();
如果(s!=null&&s.length()>=4){
字。加上(s);
}
}
}catch(filenotfounde异常){
System.out.println(“文件”+FNAME+“未找到”);
e、 printStackTrace();
系统退出(-1);
}
//从单词列表生成词典
for(字符串字:字){
生成灰烬(单词);
}
}
专用静态密码(字符串fname){
文件pfile=新文件(fname);
尝试(扫描仪输入=新扫描仪(pfile);){
while(input.hasNext()){
字符串s=input.nextLine();
字符串[]t=s.split(“,”);
字符串userid=t[0];
字符串hashedPassword=t[1];
字符串密码=dictionary.get(hashedPassword);
if(密码!=null){
System.out.println(“破解-用户:+userid+”有密码:+password);
}
}
}捕获(FileNotFoundException ex){
System.out.println(例如getMessage());
例如printStackTrace();
系统退出(-1);
}
}
私有静态void generatehash(字符串字){
//将单词转换为小写,生成哈希,存储字典条目
字符串s=word.toLowerCase();
字符串hashedStr=HashUtils.hashPassword;
dictionary.put(hashedStr,s);
//将单词大写,生成哈希,存储字典条目
s=s.substring(0,1).toUpperCase()+s.substring(1);
hashedStr=HashUtils.hashPassword;
dictionary.put(hashedStr,s);
}
}
非常简单,请查看以下内容:
public static void main(String[] args) {
List<String> words = new ArrayList<>();
List<Thread> threads = new ArrayList<>();
int numThreads = 4;
int threadsSlice = words.size() / numThreads;
for(int i = 0; i < numThreads; i++) {
Thread t = new Thread(new WorkerThread(i * threadsSlice, (i + 1) * threadsSlice, words));
t.start();
threads.add(t);
}
threads.forEach(t -> {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
static class WorkerThread implements Runnable {
private final int left;
private final int right;
private final List<String> words;
public WorkerThread(int left, int right, List<String> words) {
this.left = left;
this.right = right;
this.words = words;
}
@Override
public void run() {
for (int i = left; i < right; i++) {
generateHashes(words.get(i));
}
}
}
publicstaticvoidmain(字符串[]args){
List words=new ArrayList();
List threads=new ArrayList();
int numThreads=4;
int threadsSlice=words.size()/numThreads;
for(int i=0;i{
试一试{
t、 join();
}捕捉(中断异常e){
e、 printStackTrace();
}
});
}
静态类WorkerThread实现Runnable{
左二等兵;
私权;
私人最终列表词;
公共WorkerThread(int left、int right、列表字){
this.left=左;
这个。右=右;
这个单词=单词;
}
@凌驾
公开募捐{
for(int i=左;i<右;i++){
生成灰烬(words.get(i));
}
}
}
这段代码创建了4个线程,每个线程扫描列表的一个分区,并对分区中的所有单词应用generatehash
方法
您可以将单词
放入堆内存中,以避免通过构造函数参数将其传递给每个线程
还要确保在
generatehash
方法中为词典使用ConcurrentMap
,有许多方法可以加快执行过程,1。使用Java NIO文件读取或BufferedInputStream,2。当涉及到多线程时,您需要将文件分块并读取它,然后合并它们并使用一些同步机制。3.微调算法。