Correct use of Java Sync Lock

Source: Internet
Author: User

Synchronization lock Category Object Lock (This) class lock (the class's bytecode file object is the class name. Class) string lock (more special) scenario

Secure operation of shared resources under multiple threads.

Requirement: Start 5 threads to secure the shared resources total.

The use of synchronous lock in multi-threaded single case mode

The above three types of synchronization locks are available.

PackageCn.mythread;

Public classMyThreadImplementsRunnable {
private static int Total= 10;
@Override
Public voidRun () {
synchronized( This){//Use this object lock
//synchronized (mythread.class) {//Use Mythread.class class lock
Synchronized ("") {
//Use string lock
System. out. println (Thread.CurrentThread(). GetName () +"is running ");
Try{
Thread.Sleep(100);
}Catch(Interruptedexception e) {
E.printstacktrace ();
}
Total--;
System. out. println ( Total);
System. out. println (Thread.CurrentThread(). GetName () +"Thread End ");
}
}
}

PackageCn.test;

ImportCn.myThread.MyThread;

Public classTestmythread {
Public static voidMain (string[] args) {
MyThread MyThread = new MyThread ();
Thread thread =NULL;
for(inti = 1; I <= 5; i++) {
Thread =NewThread (MyThread,"thread "+i); // open 5 threads, passing in the same object
Thread.Start ();
}
}
}

Thread 1 is running

9

Thread 1 Thread End

Thread 3 is running

8

Thread 3 Thread End

Thread 5 is running

7

Thread 5 Thread End

Thread 2 is running

6

Thread 2 thread End

Thread 4 is running

5

Thread 4 Thread End

Analysis: From the running results can be seen 5 threads serial execution of the code inside the synchronization lock, because 5 threads in the synchronization lock object this point to the same object (Synchronization lock Object Mythread.class class lock is the same object, the synchronization lock Object "" string lock is the same object), So 5 threads will execute the code inside the sync lock serially.

Use error usage of synchronous lock in multi-threaded multiple cases mode

PackageCn.mythread;

Public classMyThreadImplementsRunnable {
private static int Total= 10;
@Override
Public voidRun () {
synchronized( This){//Use this object lock
System. out. println (Thread.CurrentThread(). GetName () +"is running ");
Try{
Thread.Sleep(100);
}Catch(Interruptedexception e) {
E.printstacktrace ();
}
Total--;
System. out. println ( Total);
System. out. println (Thread.CurrentThread(). GetName () +"Thread End ");
}
}
}

package cn.test;

Import Cn.myThread.MyThread;

public class Testmythread {
    public static void Main (string[] args) {
    ;     thread thread = NULL;
        for (int i = 1; I <= 5; i++) {
       ;      thread = new Thread (new MyThread () , "
Thread "+i"); // open 5 threads, incoming 5
             Thread.Start ();
       }
   }
}

Thread 2 is running

Thread 1 is running

Thread 3 is running

Thread 5 is running

Thread 4 is running

9

7

9

8

Thread 1 Thread End

Thread 5 Thread End

Thread 2 Thread End

Thread 3 Thread End

6

Thread 4 Thread End

Analysis: From the running results can be seen 5 threads parallel execution of the code inside the synchronization lock, because 5 threads in the synchronization lock object this point to 5 different objects, so 5 threads will simultaneously execute the code inside the synchronization lock.

Correct usage method One:

PackageCn.mythread;

Public classMyThreadImplementsRunnable {
private static int Total= 10;
@Override
Public voidRun () {
synchronized(MyThread. class ){//Use Mythread.class class lock
System. out. println (Thread.CurrentThread(). GetName () +"is running ");
Try{
Thread.Sleep(100);
}Catch(Interruptedexception e) {
E.printstacktrace ();
}
Total--;
System. out. println ( Total);
System. out. println (Thread.CurrentThread(). GetName () +"Thread End ");
}
}
}

package cn.test;

import cn.myThread.MyThread;

public class Testmythread {
    public static void main ( String[] (args) {
        thread thread = null ;
         for ( int i = 1; I <= 5; i++) {
             thread = New thread ( new MyThread () , " thread " +i); Span style= "Background-color: #ff00ff" > // open 5 threads, incoming 5 A different object
            thread.start ();
       
   }
}

Thread 1 is running

9

Thread 1 Thread End

Thread 5 is running

8

Thread 5 Thread End

Thread 4 is running

7

Thread 4 Thread End

Thread 3 is running

6

Thread 3 Thread End

Thread 2 is running

5

Thread 2 thread End

Analysis: From the running results can be seen 5 threads serial execution of the code inside the synchronization lock, because the synchronization lock object in 5 threads Mythread.class class lock is the same object, so 5 threads will be serially execute the code inside the synchronization lock.

Way two:

PackageCn.mythread;

Public classMyThreadImplementsRunnable {
private static int Total= 10;
@Override
Public voidRun () {
synchronized(""){//Use string lock
System. out. println (Thread.CurrentThread(). GetName () +"is running ");
Try{
Thread.Sleep(100);
}Catch(Interruptedexception e) {
E.printstacktrace ();
}
Total--;
System. out. println ( Total);
System. out. println (Thread.CurrentThread(). GetName () +"Thread End ");
}
}
}

package cn.test;

import cn.myThread.MyThread;

public class Testmythread {
    public static void main ( String[] (args) {
        thread thread = null ;
         for ( int i = 1; I <= 5; i++) {
             thread = New thread ( new MyThread () , " thread " +i); Span style= "Background-color: #ff00ff" > // open 5 threads, incoming 5 A different object
            thread.start ();
       
   }
}

Thread 1 is running

9

Thread 1 Thread End

Thread 4 is running

8

Thread 4 Thread End

Thread 5 is running

7

Thread 5 Thread End

Thread 3 is running

6

Thread 3 Thread End

Thread 2 is running

5

Thread 2 thread End

Analysis: From the running results can be seen 5 threads serial execution of the code inside the synchronization lock, because 5 threads in the synchronization lock object "" string lock is the same object, so 5 threads will be serially execute the code inside the synchronization lock.

Correct use of Java Sync Lock

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.