Skip to content
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

Update Java 并发.md #1

Merged
merged 1 commit into from
Oct 28, 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
9 changes: 8 additions & 1 deletion notes/Java 并发.md
Original file line number Diff line number Diff line change
Expand Up @@ -726,7 +726,7 @@ after

[Java SE 9 Enum Thread.State](https://docs.oracle.com/javase/9/docs/api/java/lang/Thread.State.html)

## 七、J.U.C - AQS
## 七、J.U.C - AQS(AbstractQueuedSynchornizer)

java.util.concurrent(J.U.C)大大提高了并发性能,AQS 被认为是 J.U.C 的核心。

Expand Down Expand Up @@ -814,6 +814,13 @@ public class CyclicBarrierExample {
before..before..before..before..before..before..before..before..before..before..after..after..after..after..after..after..after..after..after..after..
```

### Exchanger
Java中的Exchanger类是一个同步工具类,用于在两个线程之间交换数据。它提供了一个exchange()方法,当两个线程都调用该方法时,它们会被阻塞,直到彼此都调用了该方法,然后交换数据并返回。

Exchanger类的实现原理是基于AQS(AbstractQueuedSynchronizer)同步器。当一个线程调用exchange()方法时,它会尝试获取同步器的锁,如果同步器的状态为0,则表示没有其他线程在等待交换数据,该线程会将自己加入到同步器的等待队列中,并阻塞自己。当另一个线程也调用了exchange()方法时,它会尝试获取同步器的锁,如果同步器的状态为1,则表示有一个线程在等待交换数据,该线程会将自己从等待队列中取出,并与另一个线程交换数据,然后释放同步器的锁,使得两个线程都可以继续执行。

需要注意的是,Exchanger类只能用于两个线程之间交换数据,如果需要多个线程之间交换数据,可以使用CyclicBarrier或CountDownLatch等其他同步工具类。

### Semaphore

Semaphore 类似于操作系统中的信号量,可以控制对互斥资源的访问线程数。
Expand Down