Mutual exclusion lock
Only one thread can access the locked data at a time.
Spin lock
If the spin lock has been maintained by another execution unit, the caller keeps waiting until the holder of the spin lock released the lock.
Read-write lock
Divide visitors into readers and writers. Readers only read and access shared resources, while writers write shared resources. The writer is exclusive. A read-write lock can only have one writer or multiple readers at the same time, but it cannot have both readers and writers.
Blocking lock
Change the running state of threads .The thread enter the blocking state to wait until the corresponding signal (wake up, time) is obtained and it can enter the ready state. All threads in the ready state enter the running state through competition.
Fair lock
Check whether there are threads waiting in line before locking and give priority to threads waiting in line. first come, first served.
Unfair lock
Dob’t consider the queue waiting problem. Try to get the lock directly, and go to end of the queue if it can’t get the lock.
Mutual Exclusion
A resource can be held by one process at a time.
Hold and Wait
A process holds resources and requests resources held by other processes.
No Preemption
A resource held by one process can’t be preempted by another process.
Circular Wait
Every process is waiting for other processes to release resources.
public class Deadlock {
public static String str1 = "str1";
public static String str2 = "str2";
public static void main(String[] args){
Thread a = new Thread(() -> {
synchronized(Deadlock.str1){
System.out.println(Thread.currentThread().getName()+"lock str1");
Thread.sleep(1000);
synchronized(Deadlock.str2){
System.out.println(Thread.currentThread().getName()+"lock str2");
}
}
});
Thread b = new Thread(() -> {
synchronized(Deadlock.str2){
System.out.println(Thread.currentThread().getName()+"lock str2");
Thread.sleep(1000);
synchronized(Deadlock.str1){
System.out.println(Thread.currentThread().getName()+"lock str1");
}
}
});
a.start();
b.start();
}
}
Static Allocation Strategy
Break Hold and Wait: A process must apply for all the resources it needs before execution.
Hierarchical Allocation Strategy
Break Circular Wait: All resources are divided into multiple levels. After a process gets a resource, it can only apply for the next higher level of resources. When a process wants to release a resource at a certain level, it must first release the resources occupied by the higher level.
Dijkstra’s Banker algorithm:
When a process applies for the use of resources, the banker algorithm first tests and assigns the process resources, and then determines whether the system is in a safe state after allocation. If it is not safe, the allocation is invalid, so that the process will continue to wait. If it can enter a safe state, it will allocate resources to the process.
Process-Resource Allocation Graph: