Detailed explanation of Java uses synchronization block synchronized of) to ensure concurrency security

  • 2021-07-10 19:59:39
  • OfStack

In this paper, we share the specific code of Java using synchronization block synchronized () to ensure concurrency security for your reference. The specific contents are as follows


package day10;
/**
 *  Synchronization block 
 *  Effectively reduce the synchronization range 
 *  It can improve concurrency efficiency as much as possible while ensuring concurrency security 
 * 
 *  Example: Simulate two people entering the store to buy clothes at the same time, in order to improve efficiency 
 * 	      The synchronous queuing process is only carried out in the fitting stage, and there is no need to queue in other stages. 
 * @author kaixu
 *
 */
public class SyncDemo2 {

	public static void main(String[] args) {
	shop shop = new shop();
	Thread t1 = new Thread(){
		public void run() {
			shop.buy();
		}
	};
	Thread t2 = new Thread(){
		public void run() {
			shop.buy();
		}
	};
	t1.start();
	t2.start();
	}
}
class shop{
	public void buy(){
		// Get the run buy The thread of the method 
		Thread t = Thread.currentThread();
		try{
			System.out.println(t.getName()+": Picking out clothes ...");
			Thread.sleep(5000);
			/**
			 *  A synchronous block may require multiple threads to queue code within the block for execution 
			 *  But the premise is that the monitor object (that is, the locked object) is synchronized 
			 *  Requires multiple threads to see the same 1 A. 
			 * synchronized( Synchronization Monitor Object ){
			 * 		 Code that needs to be synchronized 
			 * }
			 *  Synchronous execution means that multiple threads must be queued for execution 
			 *  Asynchronous execution means that multiple threads can execute at the same time 
			 */
			synchronized (this) {
				System.out.println(t.getName()+": Trying on clothes ...");
				Thread.sleep(5000);
			}
			System.out.println(t.getName()+": Check out and leave. ");
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Related articles: