-
Notifications
You must be signed in to change notification settings - Fork 0
/
concurrency.md
1636 lines (1296 loc) · 45.6 KB
/
concurrency.md
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
# 并发
## 走进并行世界
### 你必须知道的几个概念
- 同步(Synchronous)和异步(Asynchronous)[^java-multithread]
- 并发(Concurrency)和并行(Parallelism)
- 临界区:一种公共资源或共享数据,可被多个线程使用
- 阻塞(Blocking)和非阻塞(Non-Blocking)
- 死锁(Deadlock)、饥饿(Starvation)和活锁(Livelock)
### 并发级别
- 阻塞(Blocking)
- 无饥饿(Starvation-Free):解决公平问题。
- 无障碍(Obstruction-Free):都可以进入临界区,出现问题回滚。
- 无锁(Lock-Free):都进入临界区,且有一个在有限步可以得到执行。
- 无等待(Wait-Free):都进入临界区,都可以在有限步得到执行。
### 两个重要定律
- Amdahl 定律:加速比的计算公式和理论上限。
- Gustafson 定律:同上,以不同的角度分析问题。
### Java 内存模型(JMM)
- 原子性(Atomicity):多个线程不会互相干扰。
- 可见性(Visibility):一个线程修改了值之后,其他线程能否立马看到结果。
- 有序性(Ordering):编译器可能对代码重新排序,导致多线程运算结果出错。
``````{admonition} 一个不符合原子性的例子
:class: dropdown
```{code-block} java
/**
* 测试原子性,确保运行环境为 32 位虚拟机
* 64 位机器不会出现问题
*/
public class MultiThreadLong {
public static long t = 0;
public static class ChangeT implements Runnable {
private long to;
public ChangeT(long to) {
this.to = to;
}
@Override
public void run() {
while(true) {
MultiThreadLong.t = to;
Thread.yield();
}
}
}
public static class ReadT implements Runnable {
@Override
public void run() {
while(true) {
long tmp = MultiThreadLong.t;
if (tmp != 111L && tmp != -999L && tmp != 333L && tmp != -444L) {
System.out.println(tmp);
}
Thread.yield();
}
}
}
public static void main(String[] args) {
new Thread(new ChangeT(111L)).start();
new Thread(new ChangeT(-999L)).start();
new Thread(new ChangeT(333L)).start();
new Thread(new ChangeT(-444L)).start();
new Thread(new ReadT()).start();
}
}
```
``````
### 不能指令重排的指令
- 一个线程内语义的串行性
- `volatile` 写先于读,保证可见性
- 解锁先于加锁
- 线程的 `start()` 先于它的每个动作
- 线程操作先于 `Thread.join()`
- `interrupt()` 先于中断后的代码
- 构造函数先于 `finalize()`
## Java 并行程序基础
### 有关线程你必须知道的事
- 进程是线程的容器,线程是最基本的执行单元。
- 线程间的切换和调度的成本远远小于进程。
线程的几种基本状态,在 Thread 中的 State 枚举中定义了:
```{code-block} java
public enum State {
NEW, // 创建态:操作系统为新进程分配资源,创建 PCB
RUNNABLE, // 就绪态或运行态:等待 CPU 分配时间片
BLOCKING, // 阻塞态:因 synchronized 阻塞,等待解锁
WAITING, // 等待态:等待唤醒继续执行
TIMED_WAITING, // 超时等待态:等待唤醒或时间片到继续执行
TERMINATED; // 终止态:操作系统回收资源,撤销 PCB
}
```
```{figure} ../_static/images/java-thread.jpg
Java 线程状态图
```
### 初识线程:线程的基本操作
#### 新建线程
方法一:通过继承 `Thread` 类,重写 `run()` 方法。
```{code-block} java
public class NewThead {
public static void main(String[] args) {
Thread t1 = new Thread() {
@Override
public void run() {
System.out.println("hello world");
}
};
t1.start();
}
}
```
方法二:通过实现 `Rannable` 接口。
```{code-block} java
public class NewThread2 implements Runnable {
@Override
public void run() {
System.out.println("hello world");
}
public static void main(String[] args) {
Thread t1 = new Thread(new NewThread2());
t1.start();
}
}
```
#### 终止线程
应当尽量避免使用 `stop()` 方法,它会强制线程终止,释放所有的锁,进而导致一些不一致性问题。
```{code-block} java
public class StopThread {
public static User u = new User();
public static class User {
private int id;
private String name;
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public User() {
id = 0;
name = "0";
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
public static class ChangeObjectThread extends Thread {
@Override
public void run() {
while(true) {
synchronized(u) {
int v = (int)(System.currentTimeMillis()/1000);
u.setId(v);
// Oh, do sth. else
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
u.setName(String.valueOf(v));
}
Thread.yield(); // 谦让出 CPU 的使用权,下次循环的时候再次竞争
}
}
}
public static class ReadObjcetThread extends Thread {
@Override
public void run() {
while(true) {
synchronized(u) {
if (u.getId() != Integer.parseInt(u.getName())) {
System.err.println(u.toString());
}
}
Thread.yield();
}
}
}
public static void main(String[] args) throws InterruptedException {
new ReadObjcetThread().start();
while(true) {
Thread t = new ChangeObjectThread();
t.start();
Thread.sleep(150);
t.stop(); // 不安全,运行时打印结果所示
}
}
}
```
更为稳妥的方式是,在需要终止的线程代码中,人工设置中断标志位,让其正常结束,而不是强制终止。
```{code-block} java
public class StopThread2 {
public static User u = new User();
public static class User {
private int id;
private String name;
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public User() {
id = 0;
name = "0";
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
public static class ChangeObjectThread extends Thread {
// 设置标志位,以安全的方式终止线程
volatile boolean stopme = false;
public void stopMe() {
stopme = true;
}
@Override
public void run() {
while(true) {
// 检查标志位,是否应该停止
if (stopme) {
System.out.println("Exit by stopMe()");
break;
}
synchronized(u) {
int v = (int)(System.currentTimeMillis()/1000);
u.setId(v);
// Oh, do sth. else
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
u.setName(String.valueOf(v));
}
Thread.yield();
}
}
}
public static class ReadObjcetThread extends Thread {
@Override
public void run() {
while(true) {
synchronized(u) {
if (u.getId() != Integer.parseInt(u.getName())) {
System.err.println(u.toString());
}
}
Thread.yield();
}
}
}
public static void main(String[] args) throws InterruptedException {
new ReadObjcetThread().start();
while(true) {
// Thread t = new ChangeObjectThread(); // 多态不能通过编译检查,因为只能调用父类有的方法
ChangeObjectThread t = new ChangeObjectThread();
t.start();
Thread.sleep(150);
t.stopMe(); // 通过设置标志位安全地停止
}
}
}
```
#### 线程中断
JDK 对上述过程提供了更好的封装,以便我们可以直接拿来使用。
```{code-block} java
public void Thread.interrupt(); // 中断线程(这句话只是设置中断标志位,并不会让一个线程终止)
public boolean Thread.isInterrupted(); // 判断线程是否别中断
public static boolean Thread.interrupted(); // 判断是否被中断,并清除当前中断状态
```
没有根据中断标志做出响应,程序并不会停止。
```{code-block} java
public class InterruptThread {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread() {
@Override
public void run() {
while(true) {
Thread.yield();
}
}
};
t1.start();
Thread.sleep(2000);
t1.interrupt(); // 只是设置了中断标志位,实际上程序并没有停止。
}
}
```
下面的代码段对中断标志位进行了判断,然后终止了线程。
```{code-block} java
public class InterruptThread2{
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread() {
@Override
public void run() {
while(true) {
if (Thread.currentThread().isInterrupted()) {
break;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println("在睡眠时被中断了,会清除中断标志位");
// 重新设置中断标志位
Thread.currentThread().interrupt();
}
Thread.yield();
}
}
};
t1.start();
Thread.sleep(2000);
t1.interrupt();
}
}
```
#### 等待(wait)和通知(notify)
`wait()` 和 `notify()` 是由 `Object` 类产生的,所以,任何对象都可以调用。
我们可以把对象想象成临界资源,在某个线程内对临界资源调用 `wait()` 方法,表示等一会儿再才能进入临界区。在临界资源上调用 `notify()` 方法,它会在候选队列中随机选一个候选人,进入临界区。
`wait()` 和 `notify()` 必须在 `synchronized` 函数中才能使用。`synchronized` 函数包含的区域就是临界区。
```{code-block} java
public class NotifyThread {
final static Object object = new Object(); // wait 和 notify 方法可以用于所有对象
public static class T1 extends Thread {
@Override
public void run() {
synchronized(object) {
System.out.println(System.currentTimeMillis() + ": T1 启动了");
try {
System.out.println(System.currentTimeMillis() + ": T1 等待某人唤醒");
object.wait(); // wait 释放 object 的锁了。
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis() + ": T1 被唤醒了,结束了");
}
}
}
public static class T2 extends Thread {
@Override
public void run() {
synchronized(object) {
System.out.println(System.currentTimeMillis() + ": T2 启动了,打算从队列中唤醒某个线程");
object.notify(); // wait 和 notify 必须放在 synchronized 语句中才能生效
System.out.println(System.currentTimeMillis() + ": T2 还要睡两秒,还没放弃锁");
try {
Thread.sleep(2000); // sleep 不会放弃锁
} catch (InterruptedException e) {
// e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Thread t1 = new T1();
Thread t2 = new T2();
t1.start();
t2.start();
}
}
```
#### 挂起(suspend)和继续执行(resume)线程
`suspend()` 和 `resume()` 是一个快要废弃的方法了,它们不安全,将会导致数据不一致性问题,如下代码所示。
```{code-block} java
public class BadSuspend {
public static Object u = new Object();
static ChangeObjectThread t1 = new ChangeObjectThread("t1");
static ChangeObjectThread t2 = new ChangeObjectThread("t2");
public static class ChangeObjectThread extends Thread {
public ChangeObjectThread(String name) {
super.setName(name);
}
@Override
public void run() {
synchronized(u) {
System.out.println("in " + getName());
Thread.currentThread().suspend(); // 挂起,但是不释放锁
}
System.out.println("线程" + getName() + "结束了");
}
}
public static void main(String[] args) throws InterruptedException {
t1.start(); // t1 进入临界区,并挂起
Thread.sleep(100); // main 线程睡眠 100 ms
t2.start(); // t2 申请进入临界区,但是 t1 在临界区,无法进入
t1.resume(); // t1 继续执行
t2.resume(); // 实际上 t2 并没有解锁成功,因为 resume 先于 suspend 执行了
t1.join(); // main 线程等待 t1 结束,实际上它正常结束了
t2.join(); // main 线程等待 t2 结束,但是 t2 没有解锁成功,陷入了死锁
}
}
```
如果非要使用,那么可以参考设置标志位的方式修改上面的代码。
```{code-block} java
public class GoodSuspend {
public static Object u = new Object();
public static class ChangeObjectThread extends Thread {
// 通过设置标志位,让线程正常终止
volatile boolean suspendme = false;
public void suspendMe() {
suspendme = true;
}
public void resumeMe() {
suspendme = false;
synchronized(this) {
notify();
}
}
@Override
public void run() {
while(true) {
synchronized(this) {
while(suspendme) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
synchronized(u) { // 两个线程竞争 u 的使用权
try {
System.out.println("in ChangeObjectThread");
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
Thread.yield();
}
}
}
public static class ReadObjectThread extends Thread {
@Override
public void run() {
while(true) {
synchronized(u) { // 两个线程竞争 u 的使用权
try {
System.out.println("in ReadObjectThread");
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
Thread.yield();
}
}
}
public static void main(String[] args) throws InterruptedException {
ChangeObjectThread t1 = new ChangeObjectThread();
ReadObjectThread t2 = new ReadObjectThread();
t1.start();
t2.start();
Thread.sleep(1000);
System.out.println("t1 挂起 4 秒,下面 4 秒只有 t2 在执行");
t1.suspendMe();
Thread.sleep(4000);
System.out.println("继续执行 t1 两个线程争抢 CPU 资源");
t1.resumeMe();
}
}
```
#### 等待线程结束(join)和谦让(yield)
`t1.join()` 是等待线程 `t1` 结束。
```{code-block} java
public class JoinThread {
public volatile static int i = 0;
public static class AddThread extends Thread {
@Override
public void run() {
for (i = 0; i < 10000000; i++);
}
}
public static void main(String[] args) throws InterruptedException {
AddThread t1 = new AddThread();
t1.start();
t1.join(); // main 线程等待 t1 线程执行完毕
System.out.println(i); // 因此结果总是 10000000
}
}
```
谦让(`yield`)是指让出 CPU 的使用权,前面很多代码段都有用到。
### volatile 和 Java 内存模型(JMM)
一般来讲,用 `volatile` 能保证数据的原子性,但是 `volatile` 无法保证 `(Integer)i++` 的原子性,
因为它的内部实现是,`(Integer)i` 每增加 1,`i` 都会指向一个新的 `Integer` 对象。
```{code-block} java
public class MultiThreadLong {
static volatile int i = 0;
public static class PlusTask implements Runnable {
@Override
public void run() {
for (int k = 0; k < 10000; k++) {
i++;
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(new PlusTask());
threads[i].start();
}
for (int i = 0; i < 10; i++) {
threads[i].join();
}
System.out.println("结果异常,这个数字总是小于 100000:" + i);
}
}
```
`volatile` 保证数据的可见性和有序性。
```{code-block} java
public class Visibility {
// private static boolean ready = false;
// private static int number = 12;
// 声明为 volatile 才能让两个线程看到一致的结果,否则看不到
private static volatile boolean ready = false;
private static volatile int number = 12;
private static class ReaderThread extends Thread {
@Override
public void run() {
while(!ready); // 准备好再执行下一句
System.out.println(number);
}
}
public static void main(String[] args) throws InterruptedException {
new ReaderThread().start();
Thread.sleep(1000);
number = 42; // main 线程修改数字,ReaderThread 线程能看到
ready = true;
Thread.sleep(1000);
}
}
```
### 分门别类的管理:线程组
```{code-block} java
public class ThreadGroupName implements Runnable {
@Override
public void run() {
String groupAndName = Thread.currentThread().getThreadGroup().getName()
+ "-" + Thread.currentThread().getName();
while(true) {
System.out.println("线程组和线程名:" + groupAndName);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ThreadGroup tg = new ThreadGroup("PrintGroup");
Thread t1 = new Thread(tg, new ThreadGroupName(), "T1"); // 将线程和线程组建立联系
Thread t2 = new Thread(tg, new ThreadGroupName(), "T2");
t1.start();
t2.start();
System.out.println(tg.activeCount()); // 看看这个 tg 线程组中有多少个活跃线程(估计值)
tg.list();
}
}
```
### 驻守后台:守护线程(Daemon)
守护线程是最后结束的线程,注意,它会在程序结束后自动退出。
但是有些线程无限循环,则不会退出,它们不属于守护线程。
```{code-block} java
public class DeamonDemo {
public static class DaemonT extends Thread {
public void run() {
while(true) {
System.out.println("I am alive");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t = new DaemonT();
t.setDaemon(true); // 设置为守护进程,驻守后台
t.start();
Thread.sleep(2000); // 所有线程结束了,守护进程自然退出
}
}
```
### 先干重要的事:线程优先级
```{code-block} java
/**
* 疑问:这两个 count 内存地址是一样的吗?
*/
public class PriorityDemo {
public static class HighPriority extends Thread {
static int count = 0;
public void run() {
while(true) {
synchronized(PriorityDemo.class) {
count++;
if (count > 10000000) {
System.out.println("HighPriority is complete");
break;
}
}
}
}
}
public static class LowPriority extends Thread {
static int count = 0;
@Override
public void run() {
while(true) {
synchronized(PriorityDemo.class) {
count++;
if (count > 10000000) {
System.out.println("LowPriority is complete");
break;
}
}
}
}
}
public static void main(String[] args) {
Thread high = new HighPriority();
Thread low = new LowPriority();
high.setPriority(Thread.MAX_PRIORITY);
low.setPriority(Thread.MIN_PRIORITY);
// 大多数情况下,high 比 low 先执行完
low.start();
high.start();
}
}
```
### 线程安全的概念与 synchronized
线程不安全的例子。
```{code-block} java
public class AccountingVol implements Runnable {
static AccountingVol instance = new AccountingVol();
static volatile int i = 0;
public static void increase() {
i++;
}
@Override
public void run() {
for (int i = 0; i < 10000000; i++) {
increase();
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(instance);
Thread t2 = new Thread(instance);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("结果小于 20000000 就是线程不安全:" + i);
}
}
```
线程安全的做法:用 `synchronized` 加锁:
- 给对象加锁:临界区是当前对象
- 给实例加锁:临界区是当前实例
- 给静态方法加锁:临界区是当前类
示例一:给实例加锁。
```{code-block} java
public class AccountingVol2 implements Runnable {
static AccountingVol2 instance = new AccountingVol2();
static int i = 0;
@Override
public void run() {
for (int j = 0; j < 10000000; j++) {
synchronized(instance) { // 给实例加锁
i++;
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(instance);
Thread t2 = new Thread(instance);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("用同步的方法保证线程安全,结果是 20000000:" + i);
}
}
```
实例二:给静态方法加锁。
```{code-block} java
public class AccountingVol3 implements Runnable {
static AccountingVol3 instance = new AccountingVol3();
static volatile int i = 0;
public static synchronized void increase() { // 给静态方法加锁
i++;
}
@Override
public void run() {
for (int i = 0; i < 10000000; i++) {
increase();
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(instance);
Thread t2 = new Thread(instance);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("用同步的方法保证线程安全,结果是 20000000:" + i);
}
}
```
### 程序中的幽灵:隐蔽的错误
#### 无提示的错误案例
计算结果溢出,也不报错,但是结果错了,出现这个问题将很难调试。
```{code-block} java
public class Overflow {
public static void main(String[] args) {
int v1 = 1073741827;
int v2 = 1431655768;
System.out.println("v1=" + v1);
System.out.println("v2=" + v2);
int ave = (v1 + v2) / 2;
System.out.println("ave=" + ave);
}
}
```
#### 并发下的 ArrayList
`ArrayList` 线程不安全的例子:容器扩容。
```{code-block} java
import java.util.ArrayList;
public class ArrayListMultiThread {
// ArrayList 并不是线程安全的,尝试用 Vector 替代也行
static ArrayList<Integer> a1 = new ArrayList<Integer>(10);
public static class AddThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 1000000; i++) {
// 两个线程在扩容的时候,内部一致性被破坏,抛出了异常
a1.add(i);
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new AddThread());
Thread t2 = new Thread(new AddThread());
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(a1.size()); // 结果并不是 2000000 条数据正常返回,而是抛出了异常
}
}
```
#### 并发下诡异的 HashMap
`HashMap` 线程不安全的例子:容器扩容。
```{code-block} java
import java.util.HashMap;
import java.util.Map;
public class HashMapMultiThread {
static Map<String, String> map = new HashMap<String, String>();
public static class AddThread implements Runnable {
int start = 0;
public AddThread(int start) {
this.start = start;
}
@Override
public void run() {
for (int i = start; i < 100000; i+=2) {
// 两个线程在赋值的时候,出现了数据的覆盖,实际数据量少了
map.put(Integer.toString(i), Integer.toBinaryString(i));
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new HashMapMultiThread.AddThread(0));
Thread t2 = new Thread(new HashMapMultiThread.AddThread(1));
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(map.size()); // 结果异常,并不是 200000 条数据全部插入成功了
}
}
```
#### 初学者常见问题:错误的加锁