Explain the mutex semaphore and multithreading waiting mechanism in Java
Mutex and semaphore are the basic concepts designed for concurrent programming in the operating system. The difference between mutex and semaphore is that for the same resource, mutex only has the concepts of 0 and 1, and semaphore is more than that. In other words, semaphores can enable resources to be accessed by multiple threads at the same time, while mutexes can only be accessed by one thread at the same time. The implementation of mutexes in Java is reetranlock. When accessing a synchronous resource, its object needs to obtain the lock through the method trylock(). If it fails, it returns false and if it succeeds, it returns true. Judge whether to access the synchronized resource according to the returned information. Look at the following example
A semaphore is equivalent to a counter. If a thread wants to access a resource, it must first obtain the semaphore of the resource, and the internal counter of the semaphore decreases by 1. If the internal counter of the semaphore is greater than 0, it means that there are available resources. When the thread uses a resource, it must release the semaphore of the resource. A function of semaphores is to specify a thread to access a resource. Only need to be initialized.
Semaphore is implemented in Java as semaphore, which passes in an integer number during initialization to specify the maximum concurrent access of synchronization resources
Countdownlatch implements a waiting mechanism, such as waiting for participants to arrive and start the meeting. During initialization, a counter is used to specify the number of wait. In concurrent programming, the solution is to wait for all threads to reach a certain point. Just start the next step, which is a bit similar to a meeting. The meeting can only start when all the participants are present
summary
The above is all about the detailed explanation of mutex, semaphore and multi-threaded waiting mechanism in Java programming. I hope it will be helpful to you.
Interested friends can learn about: Java multithreaded ticket instances, Java multithreaded concurrent programming (mutex lock), etc.