Java multithreading guide for beginners (12): Use Synchronized block to synchronize Variables

Source: Internet
Author: User

We can useSynchronizedBlock to synchronize specific static or non-static methods. To implement this requirement, you must define a class variable for the methods of these features, and then use the code of these methodsSynchronizedBlock, and pass this class variable as a parameterSynchronizedBlock. The following codeDemonstrate how to synchronize specific class methods:

001 Package Mythread;
002
003 Public   Class SyncThread Extends Thread
004 {
005 Private   Static String sync =   "" ;
006 Private String methodType =   "" ;
007
008 Private   Static   Void Method (String s)
009 {
010 Synchronized (Sync)
011 {
012 Sync = S;
013 System. out. println (s );
014 While ( True );
015 }
016 }
017 Public   Void Method1 ()
018 {
019 Method ( " Method1 " );
020 }
021 Public   Static   Void StaticMethod1 ()
022 {
023 Method ( " StaticMethod1 " );
024 }
025 Public   Void Run ()
026 {
027 If (MethodType. equals ( " Static " ))
028 StaticMethod1 ();
029 Else   If (MethodType. equals ( " Nonstatic "

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.