Home > front end >  how to make multithreading work in my code?
how to make multithreading work in my code?

Time:05-25

Here is my code, pls tell me why multithreading may not work for me. When I run the code, I get the same result with one thread, with two and three

I need to make it so that when I run a pod on a different number of threads, the speed increases, because I use threads.

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);
                                }
                            }
                        }
                    }
                }
            }
        }
 
    }
}

CodePudding user response:

Well, if I understand you question correctly, the problem is that you run the exact code 3 times on the same password.

If you want to really use multithreading, try to check 3 passwords, one after the other without using of threads, and then try to check 3 passwords like you done here.

  • Related