java – Runnable. When can tostring() return duplicate strings?
this. When might tostring() return a duplicate string?
public static void main(java.lang.String s[]) { for(int i=0;i<155000;i++) { new Thread(new Runnable() { public void run() { System.out.println(this.toString()); } }).start(); } }
Solution
Thomas's answer is correct because the object's default toString () method will be called, which generates different strings for different objects
There is one thing to note Object. Tostring() returns:
return getClass().getName() + "@" + Integer.toHexString(hashCode());
It includes object hashCode(). The Javadoc of hashcode () indicates:
The key is that hashcode () will be different for different objects Since your code does not store the created runnables, they will be garbage collected once the threads complete Once an object is deleted from memory, another object can occupy a place in memory. The new runnable may provide the same hash code returned by the previous runnable, and the hash code no longer exists
So in theory, you might see the same string printed indefinitely (although the chance is small)