如何让多线程在我的代码中工作?

how to make multithreading work in my code?

这是我的代码,请告诉我为什么多线程可能不适合我。当我 运行 代码时,我用一个线程得到相同的结果,用两个和三个

我需要这样做,以便当我 运行 一个 pod 在不同数量的线程上时,速度会提高,因为我使用了线程。

public class BruteForce {
public static void main(String[] args) {
     String userPassword = "zaaaaa";
     int passLenght = userPassword.length();
     long startTime = System.currentTimeMillis();
     Thread thread1 = new Thread (new Algorithm(passLenght, userPassword));
     Thread thread2 = new Thread (new Algorithm(passLenght, userPassword));
    thread1.start();
    thread2.start();
    try {
        thread1.join();
        thread2.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    long endTime = System.currentTimeMillis();
    System.out.println("Calculated in " +
            (endTime - startTime) + " milliseconds");
}
public class Algorithm implements Runnable {
    private int LENGTH;
    private boolean done = false;
    private String password;
    public Algorithm(int passLenght, String password){
        this.LENGTH = passLenght;
        this.password = password;
    }

    @Override
    public void run() {
        char[] chars = new char[LENGTH];

        if(LENGTH == 5){
            for (chars[0] = 'a'; chars[0] <= 'z' && !done; chars[0]++) {
                for (chars[1] = 'a'; chars[1] <= 'z' && !done; chars[1]++) {
                    for (chars[2] = 'a'; chars[2] <= 'z' && !done; chars[2]++) {
                        for (chars[3] = 'a'; chars[3] <= 'z' && !done; chars[3]++) {
                            for (chars[4] = 'a'; chars[4] <= 'z' && !done; chars[4]++) {
                                String template = new String(chars);
                                if(password.matches(template)){
                                    done = true;
                                    password = template;
                                    System. out. println("Your password: " + password);
                                }
                            }
                        }
                    }
                }
            }
        }
 
    }
}

好吧,如果我理解你的问题是正确的,问题是你在同一个密码上 运行 了 3 次确切的代码。

如果你想真正使用多线程,尝试检查3个密码,一个接一个不使用线程,然后像你在这里做的那样尝试检查3个密码。