Synchronized code block and synchronization method of synchronized

1. Synchronized synchronization keyword
here involves multiple threads to process shared resources, here it is necessary to "queue" the threads, the keyword used is synchronized (synchronization), in the program, to the code for processing shared resources Add this keyword to the part (the entire method or code block). It is equivalent to locking the code block, the thread that obtains the key operates on the resource, and then hands the key to other threads after completion, which ensures that only one thread can modify the same resource at a certain time.

Synchronization code block

synchronized(lock){
    
    
操作共享资源代码块
}

lock is a lock object, it is the key to the synchronization code block. When a thread executes a synchronization code block, it first checks the flag bit of the lock object. By default, the flag bit is 1. At this time, the thread executes the synchronization code block and sets the flag position of the lock object to 0. When a new thread executes When this synchronization code block is reached, because the flag bit of the lock object is 0, the new thread will be blocked. After the current thread finishes executing the synchronization code block, the flag bit of the lock object is set to 1, and the new thread can enter the synchronization code block. Execute the code in it. Repeatedly until the shared resources are processed. This process is like a public telephone booth. Only the person behind can make the call after the person in front comes out.

note:

  1. The lock object in the synchronization code block can be any type of object, but the lock object shared by multiple threads must be unique. "Any" refers to the type of shared lock object. Therefore, the creation code of the lock object cannot be placed in the run() method, otherwise each thread will create a new object when it runs to the run() method, so that each thread will have a different lock, and each lock has its own Flag bit. There is no synchronization effect between threads.
public void run(){
    
     
   Object lock = new Object(); 
    //代码 
    synchronized(lock){
    
    //锁失去了意义 
         //对共享资源处理代码 
    } 
    //代码 
} 
  1. Pay attention to the subdivision lock. There can be multiple lock objects to "lock" different resources
class A{
    
     
     private Object lock1 = new Object(); 
     private Object lock2 = new Object(); 
     
     void f(){
    
     
           synchronized(lock1){
    
     
                 //访问资源P 
           } 
     } 

     void g(){
    
     
           synchronized(lock2){
    
     
                 //访问资源Q 
           } 
     } 
} 

Here is an example of buying a ticket:

//定义Ticket1类继承Runnable接口
class Ticket1 implements Runnable {
    
    
	private int tickets = 10; // 定义变量tickets,并赋值10
	**Object lock = new Object(); // 定义任意一个对象,用作同步代码块的锁**
	public void run() {
    
    
		while (true) {
    
    
			**synchronized (lock) {
    
     // 定义同步代码块**
				try {
    
    
					Thread.sleep(10); // 经过的线程休眠10毫秒
				} catch (InterruptedException e) {
    
    
					e.printStackTrace();
				}
				if (tickets > 0) {
    
    
					System.out.println(Thread.currentThread().getName()
							+ "---卖出的票" + tickets--);
				} else {
    
     // 如果 tickets小于0,跳出循环
					break;
				}
			}
		}
	}
}
public class Example {
    
    
	public static void main(String[] args) {
    
    
		Ticket1 ticket = new Ticket1(); // 创建Ticket1对象
		// 创建并开启四个线程
		new Thread(ticket, "线程一").start();
		new Thread(ticket, "线程二").start();
		new Thread(ticket, "线程三").start();
		new Thread(ticket, "线程四").start();
	}
}

operation result:

Synchronization method

Format: synchronized return value type method name ([parameter 1, …] ){}
The method modified by synchronized allows only one thread to access at a certain time, and other threads accessing the method will block until the current thread access is completed, Only other threads have the opportunity to execute the method.

// 定义Ticket1类实现Runnable接口
class Ticket1 implements Runnable {
    
    
	private int tickets = 10;
	public void run() {
    
    
		while (true) {
    
    
			saleTicket(); // 调用售票方法
			if (tickets <= 0) {
    
     
				break;
			}
		}
	}
    // 定义一个同步方法saleTicket()
	private synchronized void saleTicket() {
    
    
		if (tickets > 0) {
    
    
			try {
    
    
				Thread.sleep(10); // 经过的线程休眠10毫秒
			} catch (InterruptedException e) {
    
    
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + "---卖出的票"
					+ tickets--);
		}
	}
}
public class Example {
    
    
	public static void main(String[] args) {
    
    
		Ticket1 ticket = new Ticket1(); // 创建Ticket1对象
         // 创建并开启四个线程
		new Thread(ticket,"线程一").start();
		new Thread(ticket,"线程二").start();
		new Thread(ticket,"线程三").start();
		new Thread(ticket,"线程四").start();
	}
}


Guess you like

Origin blog.csdn.net/xun08042/article/details/113844343