Java thread synchronization is a small trap. Have you ever fallen into it?

Source: Internet
Author: User

[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 .....

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.