2

在下面的代码中,我试图打印vector对象的线程名称和哈希码值,但输出与预期不符。此外,由于对象的哈希码值不一致,因此单例被破坏vector

public class ThreadTestVector implements Runnable {

private static Vector<String> vector;

public static synchronized Vector<String> getInstance() {
    if (vector == null) {
        vector = new Vector<String>();
    }
    return vector;
}

@Override
public synchronized void run() {

    Vector<String> vector = getInstance();

    for (int i = 0; i < 10; i++) {
        vector.add(Thread.currentThread().getName());
    }
    for (int i = 0; i < vector.size(); i++) {
        System.out.println(vector.get(i) + " Hash Code "
                + vector.hashCode());
    }
    // clear the vector for values already printed
    vector.clear();
}

public static void main(String[] args) throws Exception {
    Runnable r = new ThreadTestVector();
    Runnable r1 = new ThreadTestVector();
    Runnable r2 = new ThreadTestVector();
    Runnable r3 = new ThreadTestVector();
    Thread t1 = new Thread(r);
    Thread t2 = new Thread(r1);
    Thread t3 = new Thread(r2);
    Thread t4 = new Thread(r3);
    t1.start();
    // Thread.sleep(100);
    t2.start();
    // Thread.sleep(100);
    t3.start();
    // Thread.sleep(100);
    t4.start();

}

}

执行时产生以下输出模式
Thread-0 Hash Code 924221025
Thread-0 Hash Code 1030242113
Thread-0 Hash Code 1030242113
Thread-0 Hash Code 1030242113
Thread-0 Hash Code -119973247
Thread-0 Hash Code 1030242113
Thread-0 21134 103024
Thread-0 哈希码 1030242113
Thread-0 哈希码 1030242113
Thread-0 哈希码 1030242113
Thread-0 哈希码1030242113 Thread-0 哈希码 1030242113 Thread-0 哈希码 1030242113 Thread-0 哈希码 1030242113
Thread-0 哈希码 10302421023
Thread-0 哈希码 10302421023
Thread-0 哈希

1 哈希码 1030242113
线程 1 哈希码 1030242113
线程 1 哈希码 1030242113
Thread-1 哈希码 1030242113
Thread-1 哈希码 1030242113
Thread-1 哈希码 1030242113
Thread-1 哈希码 1030242113
Thread-1 哈希码 1030242113
Thread-1 哈希码 1030242113
Thread-2 哈希码 1030242113 Thread-2 哈希码 10302421023 Thread-123
哈希码
2 哈希码 1030242113
线程 2 哈希码 1030242113
线程 2 哈希码 1030242113
线程 2 哈希码 1030242113
线程
2 哈希码 1030242113
线程 2 哈希码 1030242113
线程 2 哈希码 103024213024-21
线程代码 1030242113
线程 3 哈希代码 1030242113
线程 3 哈希代码 1030242113
线程 3 哈希代码 1030242113
线程3哈希码1030242113
线程3哈希码1030242113
线程3哈希码1030242113
线程3哈希码1030242113
线程3哈希码1030242113
线程3哈希码1030242113
线程0哈希码1901327072
线程-0哈希码1901327072
线程0 哈希码 1030242113

这一切都混乱了,哈希码值也不同。

如何修复它以使输出以同步方式打印并且哈希码值一致?

4

2 回答 2

1

你应该同步向量

if (vector != null) {
 synchronized(vector) {
for (int i = 0; i < 10; i++) {
        vector.add(Thread.currentThread().getName());
    }
    for (int i = 0; i < vector.size(); i++) {
        System.out.println(vector.get(i) + " Hash Code "
                + vector.hashCode());
    }
    // clear the vector for values already printed
    vector.clear();
}
}
于 2013-10-24T09:28:33.667 回答
1

哈希码值不同,因为 Vector 的哈希码是根据其内容计算的。

因此,您获得不同的哈希码值也就不足为奇了。

于 2013-10-24T09:30:32.370 回答