There is a string constant pool cache feature in the JVM.
Package com.leran.thread.demo1;
public class Test {
public static void Main (string[] args) {
String a = "a";
String B = "a";
System.out.println (A = = B);
}
}
Result: true;
For example:
public class Service {
public static void print (String stringparam) {
try {
Synchronized (Stringparam) {
while (true) {
System.out.println (Thread.CurrentThread (). GetName ());
Thread.Sleep (1000);
}
}
} catch (Exception e) {
E.printstacktrace ();
}
}
}
Package com.leran.thread.demo1;
public class Threada extends Thread {
Private service service;
Public Threada (service service) {
Super ();
This.service=service;
}
@Override
public void Run () {
Service.print ("AA");
}
}
Package com.leran.thread.demo1;
public class Threadb extends Thread {
Private service service;
Public threadb (service service) {
Super ();
This.service=service;
}
@Override
public void Run () {
Service.print ("AA");
}
}
Package com.leran.thread.demo1;
public class Test {
public static void Main (string[] args) {
Service service = new service ();
Threada a = new Threada (service);
A.setname ("A");
A.start ();
THREADB B = new threadb (service);
B.setname ("A");
B.start ();
}
}
The result of the output is: A A a a a ...
The result is that because the two values of string are AA and two threads hold the same lock, the thread B cannot execute. This is the problem caused by the string constant pool. So
In most cases, the synchronous synchronized code block does not use string as the lock object, but instead uses the other, such as new object () to instantiate the object, but it is not placed in the cache pool.
java-problems with the multi-threaded String constant Pool cache feature