Home  >  Article  >  Java  >  What is synchronized? How to use synchronized?

What is synchronized? How to use synchronized?

PHP中文网
PHP中文网Original
2017-06-21 13:27:182297browse

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();
    }
}

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();
    }
}

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();
    }
}

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();
    }
}

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();
    }
}

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:
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