What is mutex and semaphore in Java ? What is the main difference?

前端 未结 11 1574
梦毁少年i
梦毁少年i 2020-11-27 09:28

What is mutex and semaphore in Java ? What is the main difference ?

11条回答
  •  孤独总比滥情好
    2020-11-27 09:56

    Semaphore can be counted, while mutex can only count to 1.

    Suppose you have a thread running which accepts client connections. This thread can handle 10 clients simultaneously. Then each new client sets the semaphore until it reaches 10. When the Semaphore has 10 flags, then your thread won't accept new connections

    Mutex are usually used for guarding stuff. Suppose your 10 clients can access multiple parts of the system. Then you can protect a part of the system with a mutex so when 1 client is connected to that sub-system, no one else should have access. You can use a Semaphore for this purpose too. A mutex is a "Mutual Exclusion Semaphore".

提交回复
热议问题