JAVA thread-three methods of synchronization

Thread safe

1. The execution sequence of multithreading cannot be reproduced, but the execution result must be reproducible.

2. The incompleteness of the shared data operation of the thread will definitely cause the data to be destroyed, which will lead to the problem of unpredictable results-thread safety.

The introduction of synchronization

1. There are two built-in synchronized syntaxes in the java language: synchronized code blocks and synchronized methods (static methods and non-static methods) can solve thread safety issues.

2. First, synchronized changes parallel to serial, which of course will affect the execution efficiency of the program, and the execution speed will be affected. Secondly, the blocking of the synchronized operation thread means that the operating system controls the CPU core to switch the context. This switch itself is also time-consuming. So using the synchronized keyword will reduce the efficiency of the program.

problem:

Thread safety is an important concern in concurrent programming. It should be noted that there are two main causes of thread safety problems. One is the existence of shared data (also called critical resources), and the other is the existence of multiple threads operating and sharing data.

solution:

When there are multiple threads operating shared data, it is necessary to ensure that there is one and only one thread operating shared data at the same time, and other threads must wait until the thread has processed the data before proceeding. This method has a name called mutual exclusion lock, which can A lock that achieves the purpose of mutual exclusion access, that is, when a shared data is added to the mutex by the currently accessing thread, at the same moment, other threads can only be in a waiting state until the current thread finishes processing the lock and releases the lock

  • Every object in Java has an object lock, which is actually just a tag value on the object header
  • The goal of synchronization is actually to achieve the purpose of thread queuing execution

1. Synchronization method

Add synchronization constraints to the modification method for critical resources— synchronized
critical resources—objects that are shared by multiple threads

public class OperNum {
    
    
	private int target;  //操作的数据
	//操作数据的方法
	public synchronized void add() {
    
     //synchronized方法的同步锁为当前对象
		target++;
		System.out.println(Thread.currentThread().getName()+"add..."+target);
	}
	
	public synchronized void sub() {
    
    
		target--;
		System.out.println(Thread.currentThread().getName()+"sun..."+target);
	}
}

The principle of the above code:
When a thread is executing the add method, other threads cannot execute the add or sub method [Neither the synchronized method can be executed, because the synchronized keyword will introduce a mutex lock, and only the thread that owns the lock can execute the synchronized method , Other threads can only block and wait], synchronized is a reentrant lock, that is, the current thread can execute other synchronized methods, but other threads cannot execute synchronized methods in the current object, and can execute methods without synchronized constraints


Second, the synchronization code block

The lock here is actually designated manually and is recommended.

synchronized(){
    
     执行的代码块}


public class MyThread extends Thread {
    
    
	private static int target = 0;  //操作目标   临界资源
	private boolean flag = true;  //不是临界资源    用来判断进行加操作 还是减 操作。
	
	private static Object lock = new Object();   //人为定义一个锁;
	public MyThread(boolean flag) {
    
    
		this.flag = flag;
	}
	
	public void run() {
    
    
	for(int i = 0;i<20;i++) {
    
    
		synchronized (lock) {
    
           //synchronized (lock) 可以保证{}中的代码执行具备原子性
			if(flag)
				target++;
			else
				target--;
			System.out.println(Thread.currentThread().getName()+(flag ? "add" : "sub")+"----"+target);
		}
	}
	}
	public static void main(String[] args) {
    
    
		for(int i = 0;i<4;i++) {
    
    
			new MyThread(i%2==0).start();
		}
	}
}

Three, synchronous static method

Use the current class object as a lock, and all static methods are mutually exclusive

  • And non-static methods are not mutually exclusive, because the lock of the non-static synchronized method is the current object, not the class lock
public class OperNum {
    
    
	private static int target = 10;  //操作的数据
	 //针对操作数据的方法
	
	public synchronized  static void add() {
    
    
		target++;
		System.out.println(Thread.currentThread().getName()+"add---"+target);
	}
	
	public synchronized  static void sub() {
    
    
		target--;
		System.out.println(Thread.currentThread().getName()+"sub--"+target);
	}
}


I have time to make up the rest

Guess you like

Origin blog.csdn.net/weixin_42437438/article/details/113871662