首先,多线程不是干这个用的。多线程解决的是,在不得不等待 IO 的时间里,怎么最大程度发挥 CPU 的作用(让 CPU 忙起来)。在本贴的这个问题里,要点不在于如何获取这几十万个字符串(如果真要从硬盘文件里取,可以考虑多线程),而在于如何让 CPU 用最小的代价把“比较”计算做完。即使用单线程,也可以让 CPU 跑成 100% 了,没必要搞什么多线程。
先不说成不成立,就hashCode()的速度比一定比equals()快,看看源代码就知道了:
-------------------------------------
public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
-----------------------------------------
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}