Table of Contents
synchronized
Preface
Example
Thread synchronization method
Thread synchronization block
Detailed reasons
Note
Home Java javaTutorial What is synchronized? How to use synchronized?

What is synchronized? How to use synchronized?

Jun 21, 2017 pm 01:27 PM
synchronized

synchronized

Preface

I believe everyone has heard of thread safety issues. When learning operating systems, one knowledge point is critical resources. Simply put, only one A resource that allows one process to operate, but when we use multi-threading, we operate concurrently, and we cannot control the access and modification of only one resource at the same time. There are several operations that we want to control. Today we will talk about the second One method: thread synchronization block or thread synchronization method (synchronized)

Example

  1. The following is an examplesynchronizedUse of keywords

Thread synchronization method

public class Sychor {public void insert(Thread thread) {for (int i = 0; i < 10; i++) {
            System.out.println(thread.getName() + "输出:  " + i);
        }

    }public static void main(String[] args) {final Sychor sychor = new Sychor();

        Thread t1 = new Thread() {public void run() {
                sychor.insert(Thread.currentThread());
            };
        };

        Thread t2 = new Thread() {public void run() {
                sychor.insert(Thread.currentThread());
            };
        };

        t1.start();
        t2.start();
    }
}
Copy after login

The output result is as shown below

What is synchronized? How to use synchronized?

It can be seen from the above results that the two threads here execute the insert() method at the same time. Below we will use the original code Add the synchronized keyword to see the effect. The code is as follows:

public class Sychor {public synchronized void insert(Thread thread) {for (int i = 0; i < 10; i++) {
            System.out.println(thread.getName() + "输出:  " + i);
        }

    }public static void main(String[] args) {final Sychor sychor = new Sychor();

        Thread t1 = new Thread() {public void run() {
                sychor.insert(Thread.currentThread());
            };
        };

        Thread t2 = new Thread() {public void run() {
                sychor.insert(Thread.currentThread());
            };
        };

        t1.start();
        t2.start();
    }
}
Copy after login

I will not list the running results of the above program, you can do it yourself Try it. In short, you just add the synchronized keyword so that the threads are executed one by one. Only when one thread is executed first can another thread be executed.

Thread synchronization block

Of course we used the thread synchronization method above, we can use thread synchronization block, these two are more flexible than thread synchronization block, Just put the code that needs to be synchronized in the synchronization block. The code is as follows;

public class Sychor {public void insert(Thread thread) {synchronized (this) {for (int i = 0; i < 10; i++) {
                System.out.println(thread.getName() + "输出:  " + i);
            }
            
        }
        

    }public static void main(String[] args) {final Sychor sychor = new Sychor();

        Thread t1 = new Thread() {public void run() {
                sychor.insert(Thread.currentThread());
            };
        };

        Thread t2 = new Thread() {public void run() {
                sychor.insert(Thread.currentThread());
            };
        };

        t1.start();
        t2.start();
    }
}
Copy after login

As can be seen from the above code, this method is more flexible. , you only need to put the code methods that need to be synchronized in the synchronization block, and the code that does not need to be synchronized outside

Detailed reasons

  1. We know Each object has a lock. When we use the thread synchronization method or thread synchronization block, we actually obtain the only lock on the object. When a thread obtains this unique lock, then other The thread can only be shut out. Note that here we say it is an object, which means it is the same object. If it is a different object, it will not work because different objects have different object locks. For example, we Change the above program to the following:

public class Sychor {public void insert(Thread thread) {synchronized (this) {for (int i = 0; i < 10; i++) {
                System.out.println(thread.getName() + "输出:  " + i);
            }
        }

    }public static void main(String[] args) {//第一个线程Thread t1 = new Thread() {public void run() {
                Sychor sychor = new Sychor();   //在run() 方法中创建一个对象sychor.insert(Thread.currentThread());
            };
        };//第二个线程Thread t2 = new Thread() {public void run() {
                Sychor sychor = new Sychor();  //创建另外的一个对象sychor.insert(Thread.currentThread());
            };
        };

        t1.start();
        t2.start();
    }
}
Copy after login

It can be seen from the above results that the thread synchronization block does not work at all at this time, because They call the insert method of different objects, and obtaining the lock is different

  1. We have already said above that an object has a lock , the thread synchronization method and the thread synchronization block actually obtain the lock of the object, so the brackets of the thread synchronization block are filled with this, we all know that this is in a class Meaning

  1. A class also has a unique lock, what we said earlier is to use an object to call member methods , now if we want to call the static method in the class, then we can use the thread synchronization method or synchronization block to obtain the only lock in the class, then multiple threads can call the static method in the same class at the same time to achieve control Yes, the code is as follows:

public class Sychor {// 静态方法public static synchronized void insert(Thread thread)  
    {for(int i=0;i<10;i++)
        {
            System.out.println(thread.getName()+"输出     "+i);
        }
    }public static void main(String[] args) {//第一个线程Thread t1 = new Thread() {public void run() {
                Sychor.insert(Thread.currentThread());  //直接使用类调用静态方法};
        };//第二个线程Thread t2 = new Thread() {public void run() {
                Sychor.insert(Thread.currentThread());   //直接使用类调用静态方法};
        };

        t1.start();
        t2.start();
    }
}
Copy after login

Note

  1. To achieve thread safety and synchronization Control, if you are executing a non-static synchronized method or a synchronized block in it, you must use the same object. If you are calling a static synchronized method or a synchronized block in it, you must use the same class to call it.

  1. If one thread accesses the static synchronization method, and another thread accesses the non-static synchronization method method, the two will not conflict at this time, because one is a class lock and the other is an object lock

  1. If you use a thread synchronization block, the code in the synchronization block has controlled access, but the code outside is accessible to all threads

  1. ##When an exception occurs in a thread that is executing a synchronized code block, then

    jvm will automatically release the lock occupied by the current thread, so there will be no deadlock due to exceptions

Reference article


The above is the detailed content of What is synchronized? How to use synchronized?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The principles and usage scenarios of Synchronized in Java and the usage and difference analysis of the Callable interface The principles and usage scenarios of Synchronized in Java and the usage and difference analysis of the Callable interface Apr 21, 2023 am 08:04 AM

1. Basic features 1. It starts with an optimistic lock, and if lock conflicts are frequent, it is converted to a pessimistic lock. 2. It starts with a lightweight lock implementation, and if the lock is held for a long time, it is converted to a heavyweight lock. 3. The spin lock strategy that is most likely used when implementing lightweight locks 4. It is an unfair lock 5. It is a reentrant lock 6. It is not a read-write lock 2. The JVM will synchronize the locking process Locks are divided into no lock, biased lock, lightweight lock, and heavyweight lock states. It will be upgraded sequentially according to the situation. Biased lock assumes that the male protagonist is a lock and the female protagonist is a thread. If only this thread uses this lock, then the male protagonist and the female protagonist can live happily forever even if they do not get a marriage certificate (avoiding high-cost operations). But the female supporting role appears

Java keyword synchronized principle and lock status example analysis Java keyword synchronized principle and lock status example analysis May 11, 2023 pm 03:25 PM

1. The concept of lock in Java Spin lock: When a thread acquires a lock, if the lock has been acquired by another thread, then the thread will wait in a loop, and then continue to judge whether the lock can be successfully acquired until it is acquired. The lock will exit the loop. Optimistic locking: Assuming there is no conflict, if the data is found to be inconsistent with the previously acquired data when modifying the data, the latest data will be read and the modification will be retried. Pessimistic lock: Assume that concurrency conflicts will occur, synchronize all data-related operations, and start locking from the time the data is read. Exclusive lock (write): Add a write lock to the resource. The thread can modify the resource, but other threads cannot lock it again (single write). Shared lock (read): After adding a read lock to a resource, it can only be read but not modified. Other threads can only add read locks and cannot add write locks (multiple). See as S

How to use synchronized to implement synchronization mechanism in Java? How to use synchronized to implement synchronization mechanism in Java? Apr 22, 2023 pm 02:46 PM

Summary of how to use synchronized in Java 1. When synchronized is used as a function modifier, the sample code is as follows: Publicsynchronizedvoidmethod(){//….} This is the synchronization method. So which object is synchronized locked at this time? What he locks is calling this synchronized method object. In other words, when an object P1 executes this synchronization method in different threads, they will form mutual exclusion to achieve synchronization effect. However, another object P2 generated by the Class to which this object belongs can arbitrarily call this method with the synchronized keyword added. The sample code above, etc.

What are the three synchronization methods in Java and how to use them? What are the three synchronization methods in Java and how to use them? Apr 27, 2023 am 09:34 AM

1. Explain that synchronized is our most commonly used synchronization method, and there are three main ways to use it. 2. Example//General class method synchronization synchronizedpublidvoidinvoke(){}//Class static method synchronization synchronizedpublicstaticvoidinvoke(){}//Code block synchronization synchronized(object){}The difference between these three methods is that the synchronized objects are different. Ordinary classes synchronize the object itself, static methods synchronize the Class itself, and code blocks synchronize the objects we fill in the brackets. What collections are there in Java?

What is the principle and process of Java Synchronized lock upgrade? What is the principle and process of Java Synchronized lock upgrade? Apr 19, 2023 pm 10:22 PM

Tool preparation Before we formally talk about the principle of synchronized, let's talk about spin locks first, because spin locks play a big role in the optimization of synchronized. To understand spin locks, we first need to understand what atomicity is. The so-called atomicity simply means that each operation is either not done or done. Doing all means that it cannot be interrupted during the operation. For example, to add one to the variable data, there are three steps: Load from memory into register. Add one to the value of data. Write the result back to memory. Atomicity means that when a thread is performing an increment operation, it cannot be interrupted by other threads. Only when this thread completes these three processes

Why does Java need to provide Lock instead of just using the synchronized keyword? Why does Java need to provide Lock instead of just using the synchronized keyword? Apr 20, 2023 pm 05:01 PM

Summary: The synchronized keyword is provided in Java to ensure that only one thread can access the synchronized code block. Since the synchronized keyword has been provided, why is the Lock interface also provided in the Java SDK package? Is this unnecessary reinvention of the wheel? Today, we will discuss this issue together. The synchronized keyword is provided in Java to ensure that only one thread can access the synchronized code block. Since the synchronized keyword has been provided, why is the Lock interface also provided in the Java SDK package? Is this unnecessary reinvention of the wheel? Today, let’s discuss it together

What is Java Synchronized What is Java Synchronized May 14, 2023 am 08:28 AM

What is Synchronized? Java readers are no strangers to the synchronized keyword. It can be seen in various middleware source codes or JDK source codes. For readers who are not familiar with synchronized, they only know that the synchronized keyword needs to be used in multi-threading. synchronized can ensure thread safety. It is called: mutex lock (only one thread can execute at the same time, other threads will wait), also called: pessimistic lock (only one thread can execute at the same time, other threads will wait). The JVM virtual machine will help you implement it. , developers only need to use the synchronized keyword. When using it, you need to use an object as a mutex for the lock

How many non-access modifiers are there in Java? How many non-access modifiers are there in Java? Aug 30, 2023 pm 06:01 PM

Java provides some other modifiers to provide functionality beyond visibility. These modifiers are called non-access modifiers. Static Members declared as static are common to all instances of the class. Static members are class-level members that are stored in class memory. Final This modifier is used to restrict further modifications to a variable, method, or class. The value of a variable declared final cannot be modified once it obtains its value. The Final method cannot be overridden in a subclass, nor can a subclass of the Final class be created. Abstract This modifier can be used with a class or method. You cannot apply this modifier to variables and constructors. Methods declared abstract must be modified in subclasses. You cannot instantiate a class declared abstract. Synchronous This modifier is used to control multiple threads

See all articles