File tree 2 files changed +70
-0
lines changed
src/main/java/com/crossoverjie/concurrent
2 files changed +70
-0
lines changed Original file line number Diff line number Diff line change @@ -291,6 +291,40 @@ CountDownLatch 也是基于 AQS(AbstractQueuedSynchronizer) 实现的,更多
291
291
292
292
## 线程响应中断
293
293
294
+ ``` java
295
+ public class StopThread implements Runnable {
296
+ @Override
297
+ public void run () {
298
+
299
+ while ( ! Thread . currentThread(). isInterrupted()) {
300
+ // 线程执行具体逻辑
301
+ System . out. println(Thread . currentThread(). getName() + " 运行中。。" );
302
+ }
303
+
304
+ System . out. println(Thread . currentThread(). getName() + " 退出。。" );
305
+
306
+ }
307
+
308
+ public static void main (String [] args ) throws InterruptedException {
309
+ Thread thread = new Thread (new StopThread (), " thread A" );
310
+ thread. start();
311
+
312
+ System . out. println(" main 线程正在运行" ) ;
313
+
314
+ TimeUnit . MILLISECONDS. sleep(10 ) ;
315
+ thread. interrupt();
316
+ }
317
+
318
+
319
+ }
320
+ ```
321
+
322
+ 可以采用中断线程的方式来通信,调用了 ` thread.interrupt() ` 方法其实就是将 thread 中的一个标志属性置为了 true。
323
+
324
+ 并不是说调用了该方法就可以中断线程,如果不对这个标志进行响应其实是没有什么作用的(这里对这个标志进行了判断)。
325
+
326
+ 但是如果抛出了 InterruptedException 异常,该标志就会被 JVM 重置为 false。
327
+
294
328
## 线程池 awaitTermination() 方法
295
329
296
330
## 管道通信
Original file line number Diff line number Diff line change
1
+ package com .crossoverjie .concurrent ;
2
+
3
+ import java .util .concurrent .TimeUnit ;
4
+
5
+ /**
6
+ * Function:
7
+ *
8
+ * @author crossoverJie
9
+ * Date: 16/03/2018 01:41
10
+ * @since JDK 1.8
11
+ */
12
+ public class StopThread implements Runnable {
13
+ @ Override
14
+ public void run () {
15
+
16
+ while ( !Thread .currentThread ().isInterrupted ()) {
17
+ // 线程执行具体逻辑
18
+ System .out .println (Thread .currentThread ().getName () + "运行中。。" );
19
+ }
20
+
21
+ System .out .println (Thread .currentThread ().getName () + "退出。。" );
22
+
23
+ }
24
+
25
+ public static void main (String [] args ) throws InterruptedException {
26
+ Thread thread = new Thread (new StopThread (), "thread A" );
27
+ thread .start ();
28
+
29
+ System .out .println ("main 线程正在运行" ) ;
30
+
31
+ TimeUnit .MILLISECONDS .sleep (10 ) ;
32
+ thread .interrupt ();
33
+ }
34
+
35
+
36
+ }
You can’t perform that action at this time.
0 commit comments