In order to realize a function , In the tree structure , When modifying a node name , You need to modify the node full path attribute fields of all the child nodes of this node at the same time ( similar " Parent node name / Parent node name / Child node name / Child node name " Construction ). Because it's constructing Update When the sentence is , You need to recursively query the child nodes and construct the value of the whole path , It took some time , And so on update When the sentence is , Maybe the name of a child node of a child node has changed again , It can cause conflict , So it's used synchronized, By the way, I know how to realize it , I don't have a deep understanding of the principle , Record here for future reference .

----------------------------------------------------- I'm the text divider -------------------- I'm the text divider ---------------------------

This paper mainly lists different synchronization methods , And I understand the scope of use .

as everyone knows , Synchronization has two uses : Synchronization method 、 And synchronous block .

One 、 Synchronized block

1.1 Class synchronization ( Non static methods )

· Realization way :

 public class JustPlayServiceImplSyn2 {
public JustPlayServiceImplSyn2(){
}
private static int flag = 1;
public void operate() {
synchronized(JustPlayServiceImplSyn2.class){
flag++;
try {
// Increase randomness , So that different threads can execute alternately here
Thread.sleep(new Random().nextInt(5));
} catch (InterruptedException e) {
e.printStackTrace();
}
flag--;
System.out.println("Thread: " + Thread.currentThread().getName()
+ " /Current flag: " + flag);
}
}
}

· Test code :

 public class JustPlay {
/**
* @param args
*/
public static void main(String[] args) {
new Thread("Thread-01") {
public void run() {
new JustPlayServiceImplSyn2().operate();
}
}.start(); // Start the first thread new Thread("Thread-02") {
public void run() {
new JustPlayServiceImplSyn2().operate();
}
}.start(); // Start the first thread
}
}

· Using range : Synchronization of multiple objects and threads .
The most widely used , The code is also simple , Add... To the code blocks that need to be synchronized synchronized keyword , And use... In bracket class [ Class name .class] Just go .

1.2 this Sync ( Non static methods )

· Realization way :

 public class JustPlayServiceImplSyn2 {
public JustPlayServiceImplSyn2(){
}
private static int flag = 1;
public void operate_this() {
synchronized(this){
flag++;
try {
// Increase randomness , So that different threads can execute alternately here
Thread.sleep(new Random().nextInt(5));
} catch (InterruptedException e) {
e.printStackTrace();
}
flag--;
System.out.println("Thread: " + Thread.currentThread().getName()
+ " /Current flag: " + flag);
}
}
}

· Test code :

 public class JustPlay {
/**
* @param args
*/
public static void main(String[] args) {
final JustPlayServiceImplSyn2 justplayserviceimplsyn2= new JustPlayServiceImplSyn2();
for(int i=0;i<100;i++){
new Thread("Thread-001"){
public void run() {
justplayserviceimplsyn2.operate_this();
}
}.start();
new Thread("Thread-002"){
public void run() {
justplayserviceimplsyn2.operate_this();
}
}.start();
}
}

· Using range : Synchronization of single object multithreading .

stay synchronized The key words are followed by this keyword . Use [this] Synchronization requires the same object to synchronize , Synchronization fails when there are multiple objects . Because synchronization is right this Object lock , Different objects have no effect on lock interaction

1.3 Static object synchronization ( Non static methods )

· Realization way :

 public class JustPlayServiceImpl {
private static JustPlayServiceImpl myobj = null; private JustPlayServiceImpl(){ }
public static JustPlayServiceImpl createJustPlayServiceImpl(){
if(myobj==null){
myobj = new JustPlayServiceImpl();
}
return myobj;
}
private static int flag = 1;
public void operate() {
synchronized(myobj){
flag++;
try {
// Increase randomness , So that different threads can execute alternately here
Thread.sleep(new Random().nextInt(5));
} catch (InterruptedException e) {
e.printStackTrace();
}
flag--;
System.out.println("Thread: " + Thread.currentThread().getName()
+ " /Current flag: " + flag);
}
}
}

· Test code :

 1 public class JustPlay {
2
3 /**
4 * @param args
5 */
6 public static void main(String[] args) {
7
8 for(int i=0;i<100;i++){
9 new Thread("Thread-01") {
10 public void run() {
11 JustPlayServiceImpl.createJustPlayServiceImpl().operate()) }
12 }.start(); // Start the first thread
13 new Thread("Thread-02") {
14 public void run() {
15 JustPlayServiceImpl.createJustPlayServiceImpl().operate() }
16 }.start(); // Start the second thread
17 }

· Using range : Singleton class, singleobject, multithread synchronization .

Because synchronization is a synchronization lock on an object , As long as the synchronization block object is unique , Can be synchronized . Be lazy , I'm going to turn the class directly into a singleton class , And then lock the only object .(ps: It's a little bit of a ghost animal ... Ha ha ha )

Two 、 Synchronization method

2.1 Static method synchronization

· Realization way :

 public class JustPlayServiceImplSyn2 {
public JustPlayServiceImplSyn2(){
}
private static int flag = 1;
public synchronized static void operate_static(){
flag++;
try {
// Increase randomness , So that different threads can execute alternately here
Thread.sleep(new Random().nextInt(5));
} catch (InterruptedException e) {
e.printStackTrace();
}
flag--;
System.out.println("Thread: " + Thread.currentThread().getName()
+ " /Current flag: " + flag);
}
}

· Test code :

 public class JustPlay {
/**
* @param args
*/
public static void main(String[] args) {
for(int i=0;i<100;i++){
new Thread("Thread-01") {
public void run() {
JustPlayServiceImplSyn2.operate_static();
}
}.start(); // Start the first thread new Thread("Thread-02") {
public void run() {
JustPlayServiceImplSyn2.operate_static();
}
}.start(); // Start the first thread
}
}
}

· Using range : Static method single object multithread synchronization .

Say again [ Because synchronization is a synchronization lock on an object ], And calling static methods binds classes, not objects , therefore , Synchronized static methods , It is equivalent to locking the class , And then it's synchronized . Principle and [1.1 Class synchronization ( Non static methods )] Agreement .

2.2 Non static method synchronization

2.2.1 Singleton class non static method synchronization

·  Realization way :

 public class JustPlayServiceImpl {
private static JustPlayServiceImpl myobj = null; private JustPlayServiceImpl(){ }
public static JustPlayServiceImpl createJustPlayServiceImpl(){
if(myobj==null){
myobj = new JustPlayServiceImpl();
}
return myobj;
}
private static int flag = 1; // Monomeric class This synchronization method works
public synchronized void operate2() {
flag++;
try {
// Increase randomness , So that different threads can execute alternately here
Thread.sleep(new Random().nextInt(5));
} catch (InterruptedException e) {
e.printStackTrace();
}
flag--;
System.out.println("Thread: " + Thread.currentThread().getName()
+ " /Current flag: " + flag);
}
}

· Test code :

 public static void main(String[] args) {
for(int i=0;i<100;i++){
new Thread("Thread-01") {
public void run() {
JustPlayServiceImpl.createJustPlayServiceImpl().operate2();
}
}.start(); // Start the first thread new Thread("Thread-02") {
public void run() {
JustPlayServiceImpl.createJustPlayServiceImpl().operate2();
}
}.start(); // Start the first thread
}
}
}

· Using range : Singleton class, singleobject, multithread synchronization .

The principle is the same as [1.3 Static object synchronization ( Non static methods )]

2.2.2 Non monomer class, non static method synchronization

· Realization way :

 public class JustPlayServiceImplSyn2 {
public JustPlayServiceImplSyn2(){
}
private static int flag = 1;
// For single object multithreading
public synchronized void operate2() {
flag++;
try {
// Increase randomness , So that different threads can execute alternately here
Thread.sleep(new Random().nextInt(5));
} catch (InterruptedException e) {
e.printStackTrace();
}
flag--;
System.out.println("Thread: " + Thread.currentThread().getName()
+ " /Current flag: " + flag);
}
}

· Test code :

 public class JustPlay {
/**
* @param args
*/
public static void main(String[] args) {
final JustPlayServiceImplSyn2 justplayserviceimplsyn2= new JustPlayServiceImplSyn2();
for(int i=0;i<100;i++){
new Thread("Thread-001"){
public void run() {
justplayserviceimplsyn2.operate2();
}
}.start();
new Thread("Thread-002"){
public void run() {
justplayserviceimplsyn2.operate2();
}
}.start();
}
}

· Using range : Synchronization of single object multithreading .

The principle is the same as [1.2 this Sync ( Non static methods )]

summary : For web pages, use ajax Method called many times class, Because it's multithreaded and uncontrollable, it's a single object , If you want to synchronize : The solution is :1.1、1.3、2.1、2.2.1; about 1.2 and 2.2.2, The object to be called must be the same to synchronize .

PS: I think there should be other ways , I feel like this ..... Ha ha ha ha ha ha

------------------------------------ The dividing line at the end -------------- The dividing line at the end ------------------ I have a chance to understand the underlying principle of synchronization ---- I'll write the principle then ------またね!---

Java synchronized Sync More related articles about each way

  1. java synchronized Synchronization details

    write down , Very important . Java Keywords of language , When it is used to modify a method or a block of code , Ensures that at most one thread executes the code at a time . One . When two concurrent threads access the same object object In this synchron ...

  2. Java Multithreading synchronous and asynchronous details

    java Threads Synchronous and asynchronous Thread pool 1) When multithreading is concurrent , Multiple threads request the same resource at the same time , The data of this resource will be insecure ,A Thread changed B Line The data processed by the program , and B The thread has been modified again A The mathematics of thread processing . Obviously this is due to global resources ...

  3. Java in String As synchronized Synchronization lock use details

    Java Use in String Make synchronization lock stay Java in String It's a special kind of existence , stay jdk in String After it is created, it shares the constant pool , Even in jdk1.8 Then the implementation is different , But the function is similar . With this feature ...

  4. Java Thread synchronization

     java Allow multithreading concurrency control , When multiple threads operate on a shareable resource variable at the same time ( Such as data addition, deletion, modification and query ),      It will lead to inaccurate data , Conflict with each other , So add a synchronization lock to avoid that before the thread does not complete the operation , By other threads ...

  5. Java CAS Synchronization mechanism The principle, ( Why in concurrent environment COUNT Self increasing operation is not safe ): Atomic The underlying layer of atomic class is not a traditional locking mechanism , It's unlocked CAS Mechanism , adopt CAS Mechanism to ensure the security of multithreading to modify a value .

    Wonderful understanding :  https://www.jianshu.com/p/21be831e851e ;  https://blog.csdn.net/heyutao007/article/details/19 ...

  6. java synchronized Thread synchronization mechanism details

    Java Keywords of language , When it is used to modify a method or a block of code , Ensures that at most one thread executes the code at a time . One . When two concurrent threads access the same object object In this synchronized(this ...

  7. 【 turn 】 Thread synchronization ------java synchronized Detailed explanation

    Java Keywords of language , When it is used to modify a method or a block of code , Ensures that at most one thread executes the code at a time . One . When two concurrent threads access the same object object In this synchronized(this ...

  8. java Medium sync (synchronized) Detailed explanation

    One . The beginning of the mountain : 1.synchronized Use In a program , If the code in this class might run in a multithreaded environment , So we have to consider the problem of synchronization . stay Java Language level synchronization primitives are built in --synchronized, It's also very simple ...

  9. Java Synchronized block (synchronized block) The use of,

    Java Synchronized block (synchronized block) Used to mark that a method or code block is synchronized .Java Synchronous blocks are used to avoid contention . This article introduces the following : Java Sync keywords (synchronzied) Instance method synchronization static ...

Random recommendation

  1. Blue Bridge Cup Algorithm training Torry Perplexity of ( Basic type )( Water problem , Sieve to find prime number )

    Algorithm training Torry Perplexity of ( Basic type ) The time limit :1.0s   Memory limit :512.0MB      Problem description Torry I love math since I was a child . One day , The teacher told him , image 2.3.5.7…… Such numbers are called prime numbers .Torry A sudden ...

  2. Linux Learning notes (15)shell The foundation Bash Basic function

    1 shell summary shell Is a command interpreter , Provides users with a way to Linux The kernel sends requests to run the program's interface system level program . Users can use shell start-up . Hang up . Stop even writing some programs . shell Is a powerful ...

  3. How Tomcat Works( 6、 ... and )

    This paper continues to analyze HttpProcessor class , This class implements org.apache.catalina.Lifecycle Interface and java.lang.Runnable Interface Let's analyze its constructor first /** * The ...

  4. Web Site architecture design considerations

    from http://blog.csdn.net/moshengtan/article/details/8990052 1    Web Load balancing 1.1 - Using commercial hardware The most frequently used F5 And citr ...

  5. More than one network card IP As a result of socket connect 10060 Timeout error

    problem : A legacy of taking over someone else's code bug, stay win7 Next , Set up multiple ip when , Found unable to connect to the server .XP It's not going to be , These are many ip by 192.168.1.127,172.1.1.13,10.0.0.1. ...

  6. An emergency solution to version conflict 、 How in all jar How to search for conflicts in package files ?

    maven It's a good project management tool , You can easily define a reference , So as to use the library written by others . And maven It's easy to talk to jenkins coordination , This makes it easier to package and deploy . But also because of this , We've become more stupid , ...

  7. PostegreSQL Template database

    Template database Template database is to create new database when ,PostgreSQL Will make a copy based on the template database , It will contain all the database settings and data files . CREATE DATABASE  Actually by copying an existing ...

  8. node-sass The reason and solution of installation failure

    Source :https://segmentfault.com/a/1190000010984731 windows On the use of yarn add node-sass --dev You can also install .

  9. 1.git Use the basic update submit operation of getting started

    Use... In project development git The specification of , Avoid extra workload due to nonstandard operation More lines of code git pull Submission code . Check the status git status . Add to local cache git add .( all , It can also be added individually ) ...

  10. environment variable GOPATH Use test

    Intel Core i5-8250U,Windows 10 Family Chinese ,Visual Studio Code 1.26.1 At noon , I put the environment variables GOBIN It's empty . There was an exception when I just went back to work : Use ...