[Problem]
What happens when a thread uses a String constant as a semaphore for synchronization? Have you ever used it?
package test. mult;/*** @ classname: test * @ author whwang * @ date 02:28:39 **/public class test {private string mutex = "mutex "; public void F (string flag) {system. out. println (flag + ", entry mehtodd F"); synchronized (mutex) {system. err. println (flag + ", invoke method f .... "); try {thread. sleep (10*1000);} catch (interruptedexception e) {e. printstacktrace () ;}} public static void main (string [] ARGs) {// t1test T1 = new test (); mythread thread1 = new mythread (); mythread thread2 = new mythread (); thread1.test = T1; thread2.test = T1; // t2test t2 = new test (); mythread thread3 = new mythread (); mythread thread4 = new mythread (); thread3.test = t2; thread4.test = t2; thread1.start (); thread2.start (); thread3.start (); thread4.start ();}} class mythread extends thread {test; @ override public void run () {While (true) {This. test. F (this. tostring () ;}}
The above sectionCodeThe thread thread1 and thread2 must be synchronized, and thread3 and thread4 must be synchronized. What is the result?
It means that the threads thread1, thread2, thread3, and thread4 are synchronized and merged.
The reason for this result is simple: because of the constant pool, all string constants with the value of "mutex" point to the same object.
This reminds me of another article about stringbuilder.Article:
Int value = 100; stringbuilder sb = new stringbuilder (value );
The author's intention is to construct a stringbuilder object, the initial value is "100", but it is actually opened up a char array with a length of value, if the value is larger .....