Synchronized misunderstanding of thread lock synchronized

Source: Internet
Author: User

Synchronized misunderstanding of thread lock synchronized

After synchronized is used, it does not mean that synchronized Locking methods or code blocks must be executed once before they can be redirected to other threads. But when two concurrent threads access the synchronized (this) synchronization code block of the same object, only one thread can be executed within a time period. The other thread must wait until the current thread finishes executing this code block before executing this code block. That is to say, even if a method is locked, the thread can still jump if other threads do not access this method. Example:

 1 public class test2{ 2     public static void main(String[] args) { 3         Thread a=new A2(); 4         Thread b=new B2(); 5         a.start(); 6         b.start(); 7     } 8 } 9 10 class A2 extends Thread{11     public void run(){12         show1();13     }14     public synchronized void show1(){15         for(int i=0;i<20;i++){16             System.out.print(i);17         }18     }        19 }20 21 class B2 extends Thread{22     public void run(){23         show2();24     }25     public synchronized void show2(){26         for (int i = 0; i < 20; i++) {27             System.out.print(i);28         }29     }30 }

Two threads are created to access their own lock show methods. The final result is not necessarily two consecutive 1-19. The running result is as follows:

001122334455667788991010111112121313141415161718191516171819

Therefore, synchronized is only valid for different threads that access the same method.

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.