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.