Multithreading can improve the efficiency of a coarse CPU, but also introduces split access conflicts.

 

 

/* Two threads accessing the same resource, resulting in access conflicts, resulting in inconsistent expectations.

If bufCache=1, the thread will sleep. If bufCache=1, the thread will sleep.

Thread1 also enters the thread body.

BufCache — = 0;

Thread1 wakes up from sleep, bufCache– = -1, bufCache =0; Not consistent with reality.

This is when multiple threads access the same resource at the same time, causing thread-safety issues.

* /

 

 

Solution: Add thread synchronization,

Use the Synchronized keyword to ensure that only one thread accesses the same resource at any one time,

Other threads wait for the thread to release the resource before executing.

 

1 Use the synchronized keyword to describe the access method

public sychornized void run(){}

Use the synchronzed keyword to describe fast access

sychronized (this){

if(bufCache>0){

try{

System.out.println(” The current running Thread is: “+ thread.currentThread ().getName());

Thread.sleep(1000);

}catch(Exception e){

e.printStackTrace();

}

System.out.println(thread.currentThread ().getName()+” buffer size: “+bufCache–);

}

}

When multiple threads access the same OBj, obj is locked 2 when the program is executed, and other threads can only execute until OBj is unlocked

 

Add the difference between synchronized:

This is equivalent to a thread going into sleep holding a resource (with a lock on it) and not allowing other people to use it.

This ensures that only one thread accesses the same resource at a time.