Skip to content

Update Java 并发.md #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 6, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions notes/Java 并发.md
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,7 @@ future.cancel(true);

Java 提供了两种锁机制来控制多个线程对共享资源的互斥访问,第一个是 JVM 实现的 synchronized,而另一个是 JDK 实现的 ReentrantLock。


### synchronized

**1. 同步一个代码块**
Expand Down Expand Up @@ -489,6 +490,15 @@ public static void main(String[] args) {


### 比较
| **比较点** | **synchronized** | **ReentrantLock** |
| ------------------------------------------------------------ | ------------------------------------------------------------ | ---------------------------------------------- |
| **锁的实现** | JVM实现 | JDK实现 |
| **性能** | 新版本Java已优化很多,例如自旋锁等,性能与ReentrantLock大致相同 | 与ReentrantLock大致相同 |
| **等待是否可中断**(当持有锁的线程长期不释放锁的时候,正在等待的线程可以选择放弃等待,改为处理其他事情。) | 不可中断 | 可中断 |
| **公平锁**(指多个线程在等待同一个锁时,必须按照申请锁的时间顺序来依次获得锁) | 非公平 | 默认非公平,但也可以是公平的 |
| **锁绑定多个条件** | | 一个ReentrantLock可以同时绑定多个Condition对象 |



**1. 锁的实现**

Expand Down