Java thread Synchronization

Source: Internet
Author: User

 PackageA.thread; Public classA {Private Static intx = 0;  Public voidrun () {//Synchronizing code blocks        synchronized( This) {             for(inti = 0; I < 10; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "=====;x=" +x); Try{Thread.Sleep (100); } Catch(interruptedexception e) {e.printstacktrace (); } x++; }        }    }    //Synchronization Method     Public synchronized voidAA () { for(inti = 0; I < 10; i++) {System.out. println (Thread.CurrentThread (). GetName ()+ "====;x=" +x); X++; }    }}
View Code
 PackageA.thread; Public classMAINB { Public Static voidMain (string[] args) {FinalA A1 =NewA (); thread[] Threads=NewThread[5];  for(inti = 0; I < 5; i++) {Threads[i]=NewThread (NewRunnable () { Public voidrun () {A1.AA ();                A1.run ();            }            }); Threads[i].setname ("Threads" +i);            Threads[i].start (); Try{threads[i].sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }        }         for(inti = 0; I < 5; i++) {            Try{threads[i].join (); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }}
View Code

The synchronization method---using the synchronized adornment method:

access modifier synchronized [static] data return type method name () {

...........

}

Prevents multiple threads from accessing the synchronized static method in this class at the same time. Static can be omitted, which can work on all object instances of the class.

The synchronous statement block---only mutually exclusive access to the resources of this chunk:

Synchronized (Shared object name) {

Code snippets that are synchronized

}

1) It locks the current object corresponding to the shared object name.

2) Implementing a synchronization block in a thread is typically added in the Run method.

Java thread Synchronization

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.