java中的线程排序

时间:2014-02-22 18:32:58

标签: java multithreading

初步信息: 我正在编写一个包含2组线程的程序。第1组线程每个都有一个它们所接受的字符串并计算SHA-256哈希并将该哈希粘贴到共享对象中。第2组线程各自具有与之关联的用户名和(哈希)密码。他们的工作是将他们的散列密码与共享对象中的密码进行比较以“破解”密码。

问题: 我目前正在使用它,但我正在尝试找到一种方法来确保第2组线程以与原始文件相同的顺序输出用户文件。一个问题是,一旦计算出哈希值,该程序就需要打印用户名和密码(如果找到匹配项)。如何保持此要求但仍按原始文件的顺序打印出来?以下是我的2组线程的代码(组2必须在组1之前创建)

GROUP 1 THREADS:

private static class Group1Th implements Runnable {
    private String passToHash;
    private SharedDict shared;
    private Lock lock;
    public Group1Th(String passToHash, Lock lock, SharedDict shared) {
        this.passToHash = passToHash;
        this.shared = shared;
        this.lock = lock;
    }

    public void run() {
        MessageDigest md = null;
        try {md = MessageDigest.getInstance ("SHA-256");}
        catch (NoSuchAlgorithmException e1) {e1.printStackTrace();}
        String password = this.passToHash;
        byte[] data = null;
        try {data = password.getBytes ("UTF-8");} 
        catch (UnsupportedEncodingException e) {e.printStackTrace();}

        for (int i = 1; i <= 100000; i++) {
            md.update(data);
            data = md.digest();
        }
        String hexData = Hex.toString(data);
        //System.out.println("Hash for (" + password + "): " + hexData);
        {synchronized(shared) {
            shared.hashed.add(hexData);
            shared.unhashed.add(password);
            shared.notifyAll();
        }}
    }
}

第2组线程

private static class Group2Th implements Runnable {
    private String dbUser;
    private String dbHashedPass;
    private SharedDict shared = new SharedDict();
    //lprivate int current = -1;

    public Group2Th(String dbUser, String dbHashedPass, SharedDict shared) {
        this.dbUser = dbUser;
        this.dbHashedPass = dbHashedPass;
        this.shared = shared;
        //this.current = -1;
    }

    public void run() {
        System.out.println("Hello from G2 Thread: " + this.dbUser + " ==> " + this.dbHashedPass);
        {synchronized(shared) {
            boolean broken = false;
            while (broken == false) {   
                try {
                    shared.wait();
                    for (int i=0; i < shared.hashed.size(); i++) {
                        if (shared.hashed.get(i).equals(dbHashedPass)) {
                            System.out.println(dbUser + " " + shared.unhashed.get(i));
                            broken = true;
                            break;
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }}
    }
}

1 个答案:

答案 0 :(得分:0)

您可以Group2Th等待Group1Th完成工作并死亡,以确保订购。

只需查看join()方法。