-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsection.java.util.concurrent.xml
More file actions
3570 lines (3106 loc) · 114 KB
/
section.java.util.concurrent.xml
File metadata and controls
3570 lines (3106 loc) · 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<chapter id="index"><?dbhtml dir="concurrent" ?>
<title>Java 并发编程</title>
<para>包位置 java.util.concurrent</para>
<section id="TimeUnit">
<title>TimeUnit</title>
<programlisting>
<![CDATA[
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
}
]]>
</programlisting>
</section>
<section id="ThreadLocalRandom">
<title>ThreadLocalRandom</title>
<programlisting>
<![CDATA[
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class RandomListElement {
public static void main(String[] args) {
// 初始化一个列表
List<String> list = new ArrayList<>();
list.add("元素1");
list.add("元素2");
list.add("元素3");
list.add("元素4");
list.add("元素5");
// 方法1:使用 Random 类
Random random = new Random();
String randomElement1 = list.get(random.nextInt(list.size()));
System.out.println("随机选取的元素 (使用 Random): " + randomElement1);
// 方法2:使用 ThreadLocalRandom (Java 8+)
String randomElement2 = list.get(
java.util.concurrent.ThreadLocalRandom.current().nextInt(list.size())
);
System.out.println("随机选取的元素 (使用 ThreadLocalRandom): " + randomElement2);
}
}
]]>
</programlisting>
</section>
<section id="java.util.concurrent.atomic">
<title>原子变量</title>
<section id="AtomicInteger">
<title>AtomicInteger / AtomicLong</title>
<programlisting>
<![CDATA[
AtomicInteger sequence = new AtomicInteger(1);
sequence.getAndIncrement(); // 加1操作
]]>
</programlisting>
</section>
<section id="AtomicBoolean">
<title>AtomicBoolean</title>
<programlisting>
<![CDATA[
package cn.aigcsst.conference.config;
import java.util.concurrent.atomic.AtomicBoolean;
public class AtomicService {
private AtomicBoolean isRunning = new AtomicBoolean(false);
// 开启服务
public void start() {
isRunning.set(true);
System.out.println("Service started.");
}
// 关闭服务
public void stop() {
isRunning.set(false);
System.out.println("Service stopped.");
}
// 检查服务是否正在运行
public boolean isRunning() {
return isRunning.get();
}
}
]]>
</programlisting>
</section>
<section id="AtomicReference">
<title>AtomicReference</title>
<programlisting>
<![CDATA[
private static AtomicReference<BankCard> bankCardRef = new AtomicReference<>(new BankCard("Neo",100));
]]>
</programlisting>
<section>
<title>AtomicReference</title>
<programlisting>
<![CDATA[
AtomicReference<String> atomicRef = new AtomicReference<>("Initial Value");
// 获取值
String value = atomicRef.get(); // "Initial Value"
// 设置值
atomicRef.set("New Value");
// CAS 操作
boolean success = atomicRef.compareAndSet("New Value", "Updated Value");
System.out.println(success); // true(如果当前值仍然是 "New Value")
]]>
</programlisting>
</section>
<section>
<title>线程安全的单例模式</title>
<programlisting>
<![CDATA[
class Singleton {
private static final AtomicReference<Singleton> INSTANCE = new AtomicReference<>();
public static Singleton getInstance() {
while (true) {
Singleton instance = INSTANCE.get();
if (instance != null) {
return instance;
}
instance = new Singleton();
if (INSTANCE.compareAndSet(null, instance)) {
return instance;
}
}
}
private Singleton() {
// 私有构造方法
}
}
]]>
</programlisting>
</section>
</section>
<section>
<title>值设置与获取操作</title>
<section>
<title>set() / get()</title>
<para>设置新值,使用 volatile 语义,确保新值对其他线程立即可见(遵循 happens-before 原则)。
</para>
<programlisting>
<![CDATA[
AtomicReference<String> ref = new AtomicReference<>("初始值");
ref.set("新值"); // 原子性地更新为新值
]]>
</programlisting>
<para>AtomicReference 类中的 get() 方法是最常用的读取操作,它提供了强内存顺序保证和即时可见性。
</para>
<programlisting>
<![CDATA[
import java.util.concurrent.atomic.AtomicReference;
public class StateControlExample {
private static final AtomicReference<State> state = new AtomicReference<>(State.INIT);
enum State { INIT, RUNNING, STOPPED }
public static void main(String[] args) throws InterruptedException {
// 工作线程
Thread worker = new Thread(() -> {
while (state.get() != State.STOPPED) {
System.out.println("工作中...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("工作线程已停止");
});
// 控制线程
Thread controller = new Thread(() -> {
try {
Thread.sleep(3000);
// 更新状态为 STOPPED
state.set(State.STOPPED);
System.out.println("已发送停止命令");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
worker.start();
controller.start();
worker.join();
controller.join();
}
}
]]>
</programlisting>
</section>
<section>
<title>lazySet() / setRelease()</title>
<para>lazySet()
提供了一种在高并发场景下以较低性能开销更新原子引用的方式,适用于对可见性要求不高、但对吞吐量敏感的场景。使用时需明确弱内存顺序的语义,避免在关键业务逻辑中引入不可见性问题。
</para>
<para>lazySet() 的实现如下:</para>
<programlisting>
<![CDATA[
public final void lazySet(V newValue) {
VALUE.setRelease(this, newValue);
}
]]>
</programlisting>
<para>以下示例展示了 lazySet() 在标记线程状态时的应用:</para>
<programlisting>
<![CDATA[
import java.util.concurrent.atomic.AtomicReference;
public class LazySetExample {
private static final AtomicReference<State> state = new AtomicReference<>(State.RUNNING);
enum State { RUNNING, STOPPED }
public static void main(String[] args) throws InterruptedException {
// 工作线程
Thread worker = new Thread(() -> {
while (state.get() == State.RUNNING) {
// 执行任务...
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("工作线程已停止");
});
worker.start();
// 主线程:延迟一段时间后停止工作线程
Thread.sleep(1000);
// 使用 lazySet 设置状态,不要求立即对工作线程可见
state.lazySet(State.STOPPED);
System.out.println("已发送停止命令");
worker.join();
}
}
]]>
</programlisting>
<para>AtomicReference 类中的 setRelease(V newValue) 是 Java 9
引入的原子操作,它提供了释放语义(Release Semantics)的写入操作。与普通的 set() 相比,setRelease()
在内存可见性和重排序限制上有更明确的语义,同时保持了较低的性能开销。
</para>
<programlisting>
<![CDATA[
import java.util.concurrent.atomic.AtomicReference;
public class PublishSubscribeExample {
private static final AtomicReference<String> messageRef = new AtomicReference<>(null);
public static void main(String[] args) throws InterruptedException {
// 生产者线程:准备并发布消息
Thread producer = new Thread(() -> {
// 准备数据(可能涉及多个操作)
String data = "重要消息";
int processedData = 42; // 模拟数据处理
// 使用 release 语义发布消息,确保数据准备完成后才发布
messageRef.setRelease(data);
System.out.println("消息已发布");
});
// 消费者线程:等待并读取消息
Thread consumer = new Thread(() -> {
String message;
// 使用 acquire 语义读取消息,确保看到完整的发布内容
while ((message = messageRef.getAcquire()) == null) {
System.out.println("等待消息...");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("收到消息: " + message);
});
consumer.start();
producer.start();
producer.join();
consumer.join();
}
}
]]>
</programlisting>
</section>
<section>
<title>setOpaque() / getOpaque()</title>
<para>AtomicReference 类中的 getOpaque() 方法是 Java 9
引入的一个原子操作,它提供了一种以弱内存顺序读取引用值的方式。与 get() 方法相比,getOpaque()
的可见性保证较弱,但性能开销可能更低。
</para>
<programlisting>
<![CDATA[
import java.util.concurrent.atomic.AtomicReference;
public class OpaqueReadExample {
private static final AtomicReference<String> ref = new AtomicReference<>("初始值");
public static void main(String[] args) {
// 线程1:更新值
Thread writer = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ref.set("新值");
System.out.println("写入完成: " + ref.get());
});
// 线程2:使用 getOpaque() 读取值
Thread reader = new Thread(() -> {
String value;
do {
// 使用弱内存顺序读取
value = ref.getOpaque();
System.out.println("读取到: " + value);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
} while (!"新值".equals(value));
System.out.println("最终读取到: " + value);
});
writer.start();
reader.start();
try {
writer.join();
reader.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
]]>
</programlisting>
</section>
<section>
<title>setAcquire() / getAcquire()</title>
<para>AtomicReference 类中的 getAcquire() 方法是,提供了一种以获取语义(Acquire
Semantics)读取引用值的方式。与 getOpaque() 相比,getAcquire() 提供了更强的内存可见性保证,但比
get() 更轻量。
</para>
<programlisting>
<![CDATA[
import java.util.concurrent.atomic.AtomicReference;
public class PublishSubscribeExample {
private static final AtomicReference<String> messageRef = new AtomicReference<>(null);
public static void main(String[] args) {
// 生产者线程:发布消息
Thread producer = new Thread(() -> {
// 准备数据
String data = "重要消息";
// 其他操作...
// 使用 release 语义发布消息
messageRef.setRelease(data);
System.out.println("消息已发布");
});
// 消费者线程:订阅消息
Thread consumer = new Thread(() -> {
String message;
// 使用 acquire 语义读取消息
while ((message = messageRef.getAcquire()) == null) {
System.out.println("等待消息...");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("收到消息: " + message);
});
consumer.start();
producer.start();
try {
producer.join();
consumer.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
]]>
</programlisting>
</section>
<section>
<title>setPlain() / getPlain()</title>
<para>AtomicReference 类中的 getPlain()
方法提供了最弱的内存顺序保证,用于读取引用值。与其他读取方法相比,getPlain()
的性能开销最低,但也牺牲了更多的内存可见性保证。
</para>
<programlisting>
<![CDATA[
import java.util.concurrent.atomic.AtomicReference;
public class CounterExample {
private static final AtomicReference<Integer> counter = new AtomicReference<>(0);
public static void main(String[] args) throws InterruptedException {
// 写线程:递增计数器
Thread writer = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.updateAndGet(v -> v + 1);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// 读线程:使用 getPlain() 读取计数器
Thread reader = new Thread(() -> {
int value;
while ((value = counter.getPlain()) < 1000) {
System.out.println("当前计数(getPlain): " + value);
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("最终计数: " + value);
});
writer.start();
reader.start();
writer.join();
reader.join();
}
}
]]>
</programlisting>
</section>
<section>
<title>getAndSet()</title>
<para>将引用值原子性地设置为新值,并返回旧值。</para>
<programlisting>
<![CDATA[
AtomicReference<String> ref = new AtomicReference<>("旧值");
String oldValue = ref.getAndSet("新值");
System.out.println("旧值: " + oldValue); // 输出 "旧值"
System.out.println("新值: " + ref.get()); // 输出 "新值"
]]>
</programlisting>
</section>
<section>
<title>compareAndSet()</title>
<para>CAS 操作:比较当前值是否等于预期值 expect,如果相等则原子性地将其更新为 update。</para>
<programlisting>
<![CDATA[
AtomicReference<String> ref = new AtomicReference<>("初始值");
// 只有当当前值为"初始值"时,才更新为"新值"
boolean success = ref.compareAndSet("初始值", "新值");
System.out.println("更新结果: " + success); // 输出 true
]]>
</programlisting>
</section>
</section>
</section>
<section id="ReentrantLock">
<title>ReentrantLock 锁</title>
<programlisting>
<![CDATA[
package cn.netkiller.test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test {
private final Lock lock = new ReentrantLock();
private int count;
public static void main(String[] args) throws ExecutionException, InterruptedException {
Test test = new Test();
new Thread(() -> {
while (true) {
test.add(1);
System.out.println(Thread.currentThread().getName() + ": " + test.count);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}, "线程1").start();
new Thread(() -> {
while (true) {
test.add(1);
System.out.println(Thread.currentThread().getName() + ": " + test.count);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}, "线程2").start();
new Thread(() -> {
while (true) {
test.add(1);
System.out.println(Thread.currentThread().getName() + ": " + test.count);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}, "线程3").start();
new Thread(() -> {
while (true) {
try {
Thread.sleep(1000);
System.out.println(test.count);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}, "线程1").start();
}
public void add(int n) {
count += n;
}
}
]]>
</programlisting>
<para>没有加锁,线程是无序执行的</para>
<screen>
<![CDATA[
线程2: 2
线程3: 3
线程1: 1
3
线程2: 4
线程3: 5
线程1: 6
6
线程2: 7
线程1: 8
线程3: 9
线程2: 10
10
线程1: 11
线程3: 12
12
线程1: 14
线程2: 13
线程3: 15
15
]]>
</screen>
<programlisting>
<![CDATA[
package cn.netkiller.test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test {
private final Lock lock = new ReentrantLock();
private int count;
public static void main(String[] args) throws ExecutionException, InterruptedException {
Test test = new Test();
new Thread(() -> {
while (true) {
test.add(1);
System.out.println(Thread.currentThread().getName() + ": " + test.count);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}, "线程1").start();
new Thread(() -> {
while (true) {
test.add(1);
System.out.println(Thread.currentThread().getName() + ": " + test.count);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}, "线程2").start();
new Thread(() -> {
while (true) {
test.add(1);
System.out.println(Thread.currentThread().getName() + ": " + test.count);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}, "线程3").start();
new Thread(() -> {
while (true) {
try {
Thread.sleep(1000);
System.out.println(test.count);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}, "线程1").start();
}
public void add(int n) {
lock.lock();
try {
count += n;
} finally {
lock.unlock();
}
}
}
]]>
</programlisting>
<screen>
<![CDATA[
线程3: 3
线程1: 1
线程2: 2
3
线程1: 4
线程3: 5
线程2: 6
6
线程1: 7
线程3: 8
线程2: 9
9
线程1: 10
线程2: 11
线程3: 12
12
]]>
</screen>
</section>
<section id="ConcurrentHashMap">
<title>线程安全的 HashMap(ConcurrentHashMap)</title>
<programlisting>
<![CDATA[
package cn.netkiller.test;
import java.util.concurrent.ConcurrentHashMap;
public class Test {
private final ConcurrentHashMap<String, Boolean> isComplated = new ConcurrentHashMap<String, Boolean>();
public static void main(String[] args) {
Test test = new Test();
test.isComplated.putIfAbsent("create", true);
test.isComplated.putIfAbsent("story", false);
test.isComplated.putIfAbsent("picture", true);
boolean isDone = test.isComplated.values().stream().allMatch(status -> status);
System.out.println(test.isComplated);
System.out.println(isDone);
test.isComplated.put("story", true);
isDone = test.isComplated.values().stream().allMatch(status -> status);
System.out.println(test.isComplated);
System.out.println(isDone);
}
}
]]>
</programlisting>
<section>
<title>设置键与值</title>
<para>putIfAbsent 当 key 不存在时可以设置值</para>
<programlisting>
<![CDATA[
test.isComplated.putIfAbsent("create", true);
]]>
</programlisting>
<para>put 可以覆盖已存在的值</para>
<programlisting>
<![CDATA[
test.isComplated.put("story", true);
]]>
</programlisting>
</section>
</section>
<section id="CopyOnWriteArraySet">
<title>CopyOnWriteArraySet</title>
<programlisting>
<![CDATA[
import java.util.concurrent.CopyOnWriteArraySet;
public class CopyOnWriteArraySetExample {
public static void main(String[] args) {
// 创建一个CopyOnWriteArraySet实例
CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<>();
// 启动一个线程向集合中添加元素
new Thread(() -> {
for (int i = 0; i < 10; i++) {
set.add("Item" + i);
try {
// 模拟一些延迟,使得输出更为明显
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
// 启动另一个线程来读取和打印集合中的元素
new Thread(() -> {
while (set.size() < 10) {
// 打印当前集合中的所有元素
System.out.println("Current set contents: " + set);
try {
// 等待一段时间,以便观察集合的变化
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 最后打印完整的集合内容
System.out.println("Final set contents: " + set);
}).start();
}
}
]]>
</programlisting>
</section>
<section id="BlockingQueue">
<title>队列 / 阻塞队列</title>
<section id="ConcurrentLinkedQueue">
<title>ConcurrentLinkedQueue 非阻塞队列</title>
<programlisting>
<![CDATA[
private final ConcurrentLinkedQueue<Story> queue = new ConcurrentLinkedQueue();
]]>
</programlisting>
<programlisting>
<![CDATA[
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
public class NonBlockingQueueExample {
public static void main(String[] args) {
Queue<String> queue = new ConcurrentLinkedQueue<>();
// 生产者线程
Thread producer = new Thread(() -> {
for (int i = 0; i < 10; i++) {
String message = "Msg " + i;
queue.offer(message); // 非阻塞添加
System.out.println("Produced: " + message);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
// 消费者线程
Thread consumer = new Thread(() -> {
int count = 0;
while (count < 10) {
String message = queue.poll(); // 非阻塞获取
if (message != null) {
System.out.println("Consumed: " + message);
count++;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
producer.start();
consumer.start();
}
}
]]>
</programlisting>
</section>
<section id="ArrayBlockingQueue">
<title>ArrayBlockingQueue</title>
<programlisting>
<![CDATA[
package cn.netkiller.test;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class QueueTest {
/**
* 定义装苹果的篮子
*/
public static class Basket {
// 篮子,能够容纳10个苹果
BlockingQueue<String> basket = new ArrayBlockingQueue<String>(10);
// 生产苹果,放入篮子
public void produce() throws InterruptedException {
// put方法放入一个苹果,若basket满了,等到basket有位置
basket.put("An apple");
}
// 消费苹果,从篮子中取走
public String consume() throws InterruptedException {
// get方法取出一个苹果,若basket为空,等到basket有苹果为止
return basket.take();
}
public int size() {
return basket.size();
}
}
// 测试方法
public static void testBasket() throws InterruptedException {
// 建立一个装苹果的篮子
final Basket basket = new Basket();
// 定义苹果生产者
class Producer implements Runnable {
public void run() {
try {
while (true) {
int n = random(1, 5);
for (int i = 0; i < n; i++) {
basket.produce();
}
System.out.println(System.currentTimeMillis() + " 放入" + n + "个,当前总数:" + basket.size() + "个");
Thread.sleep(random(450, 1000));
}
} catch (InterruptedException ex) {
}
}
}
// 定义苹果消费者
class Consumer implements Runnable {
public void run() {
try {
while (true) {
// 消费苹果
int n = random(1, 5);
for (int i = 0; i < n; i++) {
basket.consume();
}
System.out.println(System.currentTimeMillis() + " 取出" + n + "个,剩余数量:" + basket.size() + "个");
Thread.sleep(random(400, 1000));
}
} catch (InterruptedException ex) {
}
}
}
ExecutorService service = Executors.newCachedThreadPool();
Producer producer = new Producer();
Consumer consumer = new Consumer();
service.submit(producer);
// 延迟消费
Thread.sleep(5000);
service.submit(consumer);
// 程序运行10s后,所有任务停止
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
}
service.shutdownNow();
}
public static int random(int min, int max) {
var value = new Random().ints(min, (max + 1)).limit(1).findFirst().getAsInt();
return value;
}
public static void main(String[] args) throws InterruptedException {
QueueTest.testBasket();
}
}
]]>
</programlisting>
</section>
<section id="LinkedBlockingQueue">
<title>LinkedBlockingQueue</title>
<para>LinkedBlockingQueue是一种线程安全的阻塞队列,可以用于生产者-消费者模式,实现线程同步。</para>
<programlisting>
<![CDATA[
import java.util.concurrent.LinkedBlockingQueue;
public class BlockingSynchronizedThread {
private final LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
public void produce(int item) throws InterruptedException {
queue.put(item);
}
public int consume() throws InterruptedException {
return queue.take();
}
}
]]>
</programlisting>
<programlisting>
<![CDATA[
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class QueueThreadCommunication {
public static void main(String[] args) {
// 创建一个阻塞队列,容量为10
BlockingQueue<String> queue = new LinkedBlockingQueue<>(10);
// 生产者线程
Thread producer = new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
String message = "Message " + i;
queue.put(message); // 如果队列满,会阻塞
System.out.println("Produced: " + message);
Thread.sleep(100);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
// 消费者线程
Thread consumer = new Thread(() -> {
try {
for (int i = 0; i < 10; i++) {
String message = queue.take(); // 如果队列空,会阻塞
System.out.println("Consumed: " + message);
Thread.sleep(200);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
producer.start();
consumer.start();
}
}
]]>
</programlisting>
</section>