为什么 equals() 方法不适用于线程?

Why isn't equals() method working on Threads?

public class Test {
    public static void main(String[] args) {
        Thread t1 = new Thread();
        Thread t2 = new Thread();
        Thread t3 = t1;

        String s1 = new String();
        String s2 = new String();

        System.out.println(t1 == t3);  //true
        System.out.println(t1 == t2);  //false

        **System.out.println(t1.equals(t2));  //false**
        System.out.println(s1.equals(s2)); //true
    }
}

众所周知,Object.equals()方法用于检查内容而不是引用。因此,当您创建两个线程并对它们执行 equals() 时,到底发生了什么?

我假设线程的工作方式不同。 (我是初学者)

它们是如何工作的?

您似乎误解了 equals 的作用。

我想您已经了解到 equals 可用于逐个字符地比较字符串,而不是通过它们的引用来比较它们。然后你想,好吧,所以 equals 可以比较这样的东西!

然后,您认为这两个线程是相同的:

Thread t1 = new Thread();
Thread t2 = new Thread();

"because look! They are created the same way - with new Thread(). So they should be equal!"你以为。

然而,equals并不认为这两个线程是平等的。事实上,Thread 甚至没有覆盖 equalsString 覆盖)!因此,它使用其超类 Object 中的 equals 实现来比较引用。

因此,equals不像某些"magical"东西比较对象"logically"。它必须在子类中被覆盖。它并不总是在你想要的地方工作。

另一个例子是 Scanner,它也不会覆盖 equals

Scanner s1 = new Scanner("Hello");
Scanner s2 = new Scanner("Hello");
System.out.println(s1.equals(s2)); // false

s1s2 具有完全相同的要扫描的字符串并且它们位于字符串的完全相同的位置,但是当您将它们与 equals 进行比较时它们并不相等.