Skip to content

Commit d8655b0

Browse files
committed
✨ Introducing new features. join
1 parent b940191 commit d8655b0

File tree

2 files changed

+56
-3
lines changed

2 files changed

+56
-3
lines changed

MD/concurrent/thread-communication.md

+52
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,58 @@ synchronized(Object){
158158

159159
## join() 方法
160160

161+
```java
162+
private static void join() throws InterruptedException {
163+
Thread t1 = new Thread(new Runnable() {
164+
@Override
165+
public void run() {
166+
LOGGER.info("running");
167+
try {
168+
Thread.sleep(3000);
169+
} catch (InterruptedException e) {
170+
e.printStackTrace();
171+
}
172+
}
173+
}) ;
174+
Thread t2 = new Thread(new Runnable() {
175+
@Override
176+
public void run() {
177+
LOGGER.info("running2");
178+
try {
179+
Thread.sleep(4000);
180+
} catch (InterruptedException e) {
181+
e.printStackTrace();
182+
}
183+
}
184+
}) ;
185+
186+
t1.start();
187+
t2.start();
188+
189+
//等待线程1终止
190+
t1.join();
191+
192+
//等待线程2终止
193+
t2.join();
194+
195+
LOGGER.info("main over");
196+
}
197+
```
198+
199+
`t1.join()` 时会一直阻塞到 t1 执行完毕,所以最终主线程会等待 t1 和 t2 线程执行完毕。
200+
201+
其实从源码可以看出,join() 也是利用的等待通知机制:
202+
203+
核心逻辑:
204+
205+
```java
206+
while (isAlive()) {
207+
wait(0);
208+
}
209+
```
210+
211+
在 join 线程完成后会调用 notifyAll() 方法,是在 JVM 实现中调用,所以这里看不出来。
212+
161213
## volatile 共享内存
162214

163215
## CountDownLatch 并发工具

src/main/java/com/crossoverjie/actual/ThreadCommunication.java

+4-3
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,9 @@
1515
public class ThreadCommunication {
1616
private final static Logger LOGGER = LoggerFactory.getLogger(ThreadCommunication.class);
1717
public static void main(String[] args) throws Exception {
18-
//join();
18+
join();
1919
//executorService();
20-
countDownLatch();
20+
//countDownLatch();
2121

2222
}
2323

@@ -118,10 +118,11 @@ public void run() {
118118
}) ;
119119

120120
t1.start();
121+
t2.start();
122+
121123
//等待线程1终止
122124
t1.join();
123125

124-
t2.start();
125126
//等待线程2终止
126127
t2.join();
127128

0 commit comments

Comments
 (0)