在下面的代码中,我试图打印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哈希码924221025
Thread-0哈希码1030242113
Thread-0哈希码1030242113
Thread-0哈希码1030242113
Thread-0哈希码-119973247
Thread-0哈希码1030242113
Thread-0哈希码1030242113
Thread-0哈希码1030242113
Thread-0哈希码1030242113
Thread-0哈希码1030242113
Thread-0哈希码1030242113
Thread-0哈希码1030242113
Thread-0哈希码1030242113
Thread-0哈希码1030242113
Thread-1哈希码1030242113
Thread-1哈希码1030242113
Thread-1哈希码1030242113
Thread-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哈希码1030242113
Thread-2哈希码1030242113
Thread-2哈希码1030242113
Thread-2哈希码1030242113
Thread-2哈希码1030242113
Thread-2哈希码1030242113
Thread-2哈希码1030242113
Thread-2哈希码1030242113
Thread-2哈希码1030242113
Thread-3哈希码1030242113
Thread-3哈希码1030242113
Thread-3哈希码1030242113
Thread-3哈希码1030242113
Thread-3哈希码1030242113
Thread-3哈希码1030242113
Thread-3哈希码1030242113
Thread-3哈希码1030242113
Thread-3哈希码1030242113
Thread-3哈希码1030242113
Thread-0哈希码1901327073
Thread-0哈希码1030242113
Thread-0哈希码1030242113
这些都是混乱的,哈希码值也不同。
如何修复它以便以同步方式打印输出并且哈希码值是一致的?
答案 0 :(得分: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();
}
}
答案 1 :(得分:1)
散列码值不同,因为Vector的散列码是根据其内容计算的。
因此,您为哈希码获取不同的值并不奇怪。