File tree 2 files changed +56
-3
lines changed
src/main/java/com/crossoverjie/actual
2 files changed +56
-3
lines changed Original file line number Diff line number Diff line change @@ -158,6 +158,58 @@ synchronized(Object){
158
158
159
159
## join() 方法
160
160
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
+
161
213
## volatile 共享内存
162
214
163
215
## CountDownLatch 并发工具
Original file line number Diff line number Diff line change 15
15
public class ThreadCommunication {
16
16
private final static Logger LOGGER = LoggerFactory .getLogger (ThreadCommunication .class );
17
17
public static void main (String [] args ) throws Exception {
18
- // join();
18
+ join ();
19
19
//executorService();
20
- countDownLatch ();
20
+ // countDownLatch();
21
21
22
22
}
23
23
@@ -118,10 +118,11 @@ public void run() {
118
118
}) ;
119
119
120
120
t1 .start ();
121
+ t2 .start ();
122
+
121
123
//等待线程1终止
122
124
t1 .join ();
123
125
124
- t2 .start ();
125
126
//等待线程2终止
126
127
t2 .join ();
127
128
You can’t perform that action at this time.
0 commit comments