Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
948 lines (484 loc) · 39 KB
/
Copy pathindex.html
File metadata and controls
948 lines (484 loc) · 39 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
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>多线程 | Lin 的博客</title>
<link href="/favicon.png" rel="shortcut icon" type="image/x-icon" />
<meta name="author" content="Lin" />
<meta name="description" content="Lin 的生活记录~" />
<meta name="generator" content="Hugo 0.119.0">
<link rel="canonical" href="https://recordnote.github.io/java/threadjuc/thread/" />
<meta property="og:title" content="多线程" />
<meta property="og:description" content="1、线程实现的方式及其优缺点? 1)继承Thread类 2)实现Runnable接口 3)实现Callable(JDK>=1.5) 4)使用线" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://recordnote.github.io/java/threadjuc/thread/" /><meta property="og:image" content="https://recordnote.github.io/img/java.png" /><meta property="article:section" content="java" />
<meta property="article:published_time" content="2023-06-01T14:21:26+08:00" />
<meta property="article:modified_time" content="2023-06-01T14:21:26+08:00" />
<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://recordnote.github.io/img/java.png"/>
<meta name="twitter:title" content="多线程"/>
<meta name="twitter:description" content="1、线程实现的方式及其优缺点? 1)继承Thread类 2)实现Runnable接口 3)实现Callable(JDK>=1.5) 4)使用线"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
<link rel="stylesheet" href="/css/icomoon.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/overlayscrollbars@1.13.1/css/OverlayScrollbars.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4.0.0/github-markdown.min.css">
<link rel="stylesheet" href="/css/site.css" />
<style>
.ui.header a:not(.ui.button):hover {
text-decoration: underline;
}
a:not(.ui.button) {
color: seagreen !important;
}
.inverted a:not(.ui.button) {
color: darkseagreen !important;
}
body.default {
background-color: #fff;
background-image: url(/me/background1.jpg);
}
body.dark {
background-color: #333;
background-image: url(/me/background1.jpg);
}
</style>
<link rel="stylesheet" data-highlight href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release/build/styles/tomorrow.min.css" />
<link rel="stylesheet" href="/css/custom.css" />
</head>
<body class="default">
<nav class="ui secondary menu dream-menu dream-nav">
<div class="item">
<i class="large link bullseye icon dream-flip-toggle" title="翻转!"></i>
</div>
<div class="item">
<i class="large link home icon" title="首页" onclick="window.location.href = 'https:\/\/recordnote.github.io'"></i>
</div>
<div class="item">
<i class="large link icon theme-switch" onclick="themeSwitch()"></i>
</div>
<div class="item">
<i class="large link search icon" onclick="toggleSearch()"></i>
</div>
</nav>
<div class="flip-container">
<div class="flipper">
<section class="front">
<div class="dream-max-width">
<div class="ui relaxed centered grid dream-grid dream-grid-single">
<aside class="sixteen wide mobile sixteen wide tablet three wide computer column dream-single-aside">
<div class="ui segment toc">
<nav id="TableOfContents">
<ul>
<li><a href="#1线程实现的方式及其优缺点">1、线程实现的方式及其优缺点?</a></li>
<li><a href="#2线程的run和start的区别">2、线程的run()和start()的区别?</a></li>
<li><a href="#3进程线程协程之间的区别">3、进程、线程、协程之间的区别?</a></li>
<li><a href="#4线程状态有哪些6个">4、线程状态有哪些?(6个)</a></li>
<li><a href="#5说一下volatile关键字还有怎么保证可见性涉及内存屏障相关的">5、说一下volatile关键字,还有怎么保证可见性,涉及内存屏障相关的?</a></li>
<li><a href="#6如何死锁考察死锁的条件">6、如何死锁?(考察死锁的条件)</a></li>
<li><a href="#7如何加锁synchronize关键字和reentrantlock">7、如何加锁?(Synchronize关键字和Reentrantlock)</a>
<ul>
<li><a href="#71同步方法块和同步方法的区别monitorenterexit和acc_synchronized">7.1、同步方法块和同步方法的区别?(monitorenter、exit和ACC_SYNCHRONIZED)</a></li>
<li><a href="#72锁升级过程或者锁的优化机制重点">7.2、锁升级过程(或者锁的优化机制)?(重点)</a></li>
<li><a href="#73reentrantlock优缺点">7.3、ReentrantLock优缺点?</a></li>
<li><a href="#74底层实现aqscas">7.4、底层实现?(AQS、CAS) </a></li>
<li><a href="#75cas会存在什么问题如何避免">7.5、CAS会存在什么问题?如何避免?</a></li>
<li><a href="#76公平锁和非公平锁在aqs上是如何实现的synchonized是公平锁还是非公平锁">7.6、公平锁和非公平锁在AQS上是如何实现的?Synchonized是公平锁还是非公平锁?</a></li>
<li><a href="#77-读写锁是怎么实现的也是基于aqs的">7.7、 读写锁是怎么实现的?(也是基于AQS的)</a></li>
</ul>
</li>
<li><a href="#8线程池的理解">8、线程池的理解</a>
<ul>
<li><a href="#81线程池创建的4中方法">8.1、线程池创建的4中方法?</a></li>
<li><a href="#82任务加入的线程池的流程">8.2、任务加入的线程池的流程?</a></li>
<li><a href="#83线程池的7个参数拒绝策略">8.3、线程池的7个参数?拒绝策略?</a></li>
<li><a href="#84线程池中如何拿到线程的执行结果">8.4、线程池中如何拿到线程的执行结果?</a></li>
</ul>
</li>
<li><a href="#9threadlocal了解">9、ThreadLocal了解?</a></li>
</ul>
</nav>
</div>
</aside>
<div class="sixteen wide mobile sixteen wide tablet ten wide computer column markdown-body dream-single" id="dream-save-post-as-img">
<section class="ui top attached segment">
<header>
<h1 class="ui large header">多线程<span class="sub header">
<span class="left">
@
Lin
|
<span data-format="luxon">2023-06-01T14:21:26+08:00</span>
| 12 分钟阅读
| 更新于
<span data-format="luxon">2023-06-01T14:21:26+08:00</span>
</span>
<span class="dream-share">
<a href="#" class="save-as-image" title="保存为图片" onclick="savePostAsImg()">
<i class="save icon"></i>
</a>
<a href="https://twitter.com/intent/tweet?text=%e5%a4%9a%e7%ba%bf%e7%a8%8b&url=https%3a%2f%2frecordnote.github.io%2fjava%2fthreadjuc%2fthread%2f" title="Twitter">
<i class="twitter icon"></i>
</a>
<a href="https://facebook.com/sharer/sharer.php?u=https%3a%2f%2frecordnote.github.io%2fjava%2fthreadjuc%2fthread%2f" title="Facebook">
<i class="facebook icon"></i>
</a>
</span>
</span>
</h1>
</header>
<article class="main">
<img class="cover" src="/img/java.png" />
<h2 id="1线程实现的方式及其优缺点">1、线程实现的方式及其优缺点?</h2>
<p>1)继承Thread类</p>
<p>2)实现Runnable接口</p>
<p>3)实现Callable(JDK>=1.5)</p>
<p>4)使用线程池方式创建</p>
<p>实现Runnable接口与实现Callable接口的方式基本相同,只是Callable接口里定义的方法返回值,可以声明抛出异常而已。这种实现Runnable接口和实现Callable接口归为一种方式。</p>
<p>a、<strong>采用实现Runnable、Callable接口的方式创建线程的优缺点</strong></p>
<p><strong>优点:</strong>:线程类只是实现了Runnable或者Callable接口,<strong>还可以继承其他类</strong>,这种方式下,多个线程可以<strong>共享一个target对象</strong>,所以非常<strong>适合多个相同线程来处理同一份资源的情况</strong>,从而可以将CPU、代码和数据分开,形成清晰的模型,较好的体现了面向对象的思想。</p>
<p><strong>缺点:</strong>:编程稍微复杂一些,如果需要访问当前线程,则必须使用 Thread.currentThread() 方法。</p>
<p>b、<strong>采用继承Thread类的方式创建线程的优缺点</strong></p>
<p>**优点:**编写简单,如果需要访问当前线程,则无需使用 Thread.currentThread() 方法,直接使用this即可获取当前线程。</p>
<p><strong>缺点:</strong>:因为线程类已经继承了Thread类,Java语言是单继承的,所以就不能再继承其他父类了。</p>
<h2 id="2线程的run和start的区别">2、线程的run()和start()的区别?</h2>
<p>start() 方法被用来启动新创建的线程,而且 start() 内部调用了 run() 方法,这和直接调用run()方法的效果不一样。</p>
<p>当你调用run()方法的时候,只会是在原来的线程中调用,没有新的线程启动,start()方法才会启动新线程。</p>
<h2 id="3进程线程协程之间的区别">3、进程、线程、协程之间的区别?</h2>
<p><strong>进程</strong>:进程时程序运行和资源分配的基本单位。一个程序至少有一个进程,一个进程至少有一个线程。</p>
<p><strong>线程</strong>:线程是进程的一个实体,是cpu调度和分派的基本单位。</p>
<p><strong>协程</strong>:协程比线程更轻量级,协程不是被操作系统内核管理,是完全有程序所控制(也就是用户态执行)。这样带来的好处就是性能提高,不会像线程切换那样消耗资源。</p>
<h2 id="4线程状态有哪些6个">4、线程状态有哪些?(6个)</h2>
<p>Java线程状态:新建、可运行、阻塞、等待、超时等待、终止。</p>
<h2 id="5说一下volatile关键字还有怎么保证可见性涉及内存屏障相关的">5、说一下volatile关键字,还有怎么保证可见性,涉及内存屏障相关的?</h2>
<p><strong>volatile三特性</strong>:a、保证可见性 b、不保证复合操作的原子性 c、<strong>禁止指令重排</strong></p>
<p>1)保证了不同线程对这个变量进行操作时的<strong>可见性</strong>,即一个线程修改了某个变量的值,这新值对其他线程来说是立即可见的,volatile关键字会强制将修改的值立即写入主内存。</p>
<p>2)<strong>禁止进行指令重排序</strong>。</p>
<p>3)volatile<strong>不保证原子性</strong>。</p>
<p><strong>保证部分有序性</strong>:当程序执行到volatile变量的读操作或者写操作时,在其前面的操作的更改肯定全部已经进行,且结</p>
<p>果已经对后面的操作可见;在其后面的操作肯定还没有进行;</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-java" data-lang="java"><span style="display:flex;"><span>x <span style="color:#f92672">=</span> <span style="color:#ae81ff">2</span><span style="color:#f92672">;</span> <span style="color:#75715e">//语句1
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span>y <span style="color:#f92672">=</span> <span style="color:#ae81ff">0</span><span style="color:#f92672">;</span> <span style="color:#75715e">//语句2
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span>flag <span style="color:#f92672">=</span> <span style="color:#66d9ef">true</span><span style="color:#f92672">;</span> <span style="color:#75715e">//语句3
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span>x <span style="color:#f92672">=</span> <span style="color:#ae81ff">4</span><span style="color:#f92672">;</span> <span style="color:#75715e">//语句4
</span></span></span><span style="display:flex;"><span><span style="color:#75715e"></span>
</span></span><span style="display:flex;"><span>y <span style="color:#f92672">=</span> <span style="color:#f92672">-</span><span style="color:#ae81ff">1</span><span style="color:#f92672">;</span> <span style="color:#75715e">//语句5
</span></span></span></code></pre></div><p>由于flag变量为volatile变量,那么在进行指令重排序的过程的时候,不会将语句3放到语句1、语句2前面,也不会讲语句3放到语句4、语句5后面。但是要注意语句1和语句2的顺序、语句4和语句5的顺序是不作任何保证的。</p>
<p>使用volatile 一般用于 状态标记量 和 单例模式的双检锁。</p>
<p>**补充:JMM(java内存)模型:**主内存+本地内存(线程),本地内存会复制主内存的共享变量副本。</p>
<h2 id="6如何死锁考察死锁的条件">6、如何死锁?(考察死锁的条件)</h2>
<p>1)互斥条件:进程要求对所分配的资源进行排它性控制,即在一段时间内某资源仅为一进程所占用。
2)请求和保持条件:当进程因请求资源而阻塞时,对已获得的资源保持不放。
3)不剥夺条件:进程已获得的资源在未使用完之前,不能剥夺,只能在使用完时由自己释放。
4)环路等待条件:在发生死锁时,必然存在一个进程–资源的环形链。</p>
<h2 id="7如何加锁synchronize关键字和reentrantlock">7、如何加锁?(Synchronize关键字和Reentrantlock)</h2>
<p>(synchronized在同一个类下修饰a、b两个方法,不会造成锁竞争,如果a、b方法是static修饰 的会,因为是锁的是同一个类。)</p>
<p><strong>Synchronized的3种使用方式:</strong></p>
<ul>
<li>普通同步方法,锁的是当前实例对象,this。</li>
<li>静态同步方法,锁的是当前类的class对象。</li>
<li><strong>同步方法块,锁的是括号里面的对象</strong>。</li>
</ul>
<p><strong>Synchronized 和 ReentrantLock有什么不同</strong>:</p>
<p><strong>相似处</strong>:都是可重入锁,都是阻塞式的同步加锁。
<strong>不同处</strong>:</p>
<p><strong>a、</strong> <strong>synchronized依赖于JVM实现的</strong>,在经过编译,会在<strong>同步语句块</strong>的前后形成monitorenter和monitorexit这个两个字节码指令。<strong>ReentrantLock是基于JDK1.5之后提供的API层面</strong>的互斥锁,需要 lock() 和 unlock() 方法配合 try/finally 语句块来完成。</p>
<p><strong>b、<strong>相比synchronized,ReentrantLock提供了一些</strong>高级的功能</strong>,主要有3点:</p>
<p>1)<strong>等待可中断</strong>,持有锁的线程长期不释放的时候,正在等待的线程<strong>可以选择放弃等待</strong>,这相对于synchronized来说可以避免出现死锁的情况。</p>
<p>2)**可实现公平锁,**多个线程等待同一个锁的时候,必须按照申请锁的时间顺序获得锁,Synchronized 是非公平锁,ReentrantLock默认创建构造函数时非公平锁,可以通过参数设置true设为公平锁。</p>
<p>3)<strong>锁可以绑定多个条件</strong>,,一个 ReentrantLock 对象可以同时绑定对个对象,例如ReentrantLock可与 wait() 和 notify()/notifyall() 方法相结合实现等待/通知机制,但需要借助<code>Condition</code>接口与<code>newCondition()</code>方法。</p>
<h3 id="71同步方法块和同步方法的区别monitorenterexit和acc_synchronized">7.1、同步方法块和同步方法的区别?(monitorenter、exit和ACC_SYNCHRONIZED)</h3>
<p>同步方法,锁是用当前实例对象,编译后,字节码有一个 <code>ACC_SYNCHRONIZED</code> 标识该方法是个同步方法。</p>
<p>同步方法块锁的是 synchronized关键字括号后的对象。 编译后,字节码有<code>monitorenter</code> 和 <code>monitorexit</code> 指令.</p>
<h3 id="72锁升级过程或者锁的优化机制重点">7.2、锁升级过程(或者锁的优化机制)?(重点)</h3>
<p>从 JDK1.6之后synchronized就在不断优化锁的机制,**锁状态从低到高:**无锁 - > 偏向锁 - > 轻量级锁 - > 重量级锁。。简单说就是,偏向锁就是通过对象头的偏向线程 ID 来对比,都不需要CAS了,而轻量级锁就是通过CAS修改对象头锁记录和自旋来实现的,重量级锁是除了拥有锁的线程其他全部阻塞。</p>
<p><strong>偏向锁:</strong> 线程1访问代码块并获取锁对象,<strong>会偏向对象头和栈帧中记录偏向锁的线程 ID</strong> ,之后这个线程再次进入同步块代码就都不需要CAS来加锁和解锁了,偏向锁会永远偏向第一个获得锁的线程。</p>
<p><strong>轻量级锁:<strong>对象头中中包含有一些锁的标志位,代码进入同步块的时候,<strong>会使用CAS方式来尝试获取锁</strong>,如果</strong>更新成功</strong>则会把对象头中的状态位标记<strong>为轻量级锁</strong>,如果<strong>更新失败</strong>,当前线程就尝试<strong>自旋来获得锁</strong>。</p>
<p><strong>简要过程:</strong> <strong>线程1</strong>访问代码块并获取锁对象,<strong>会在 Java 对象头和栈帧中记录偏向的锁的 线程ID</strong>,而且偏向锁不会主动释放锁,当<strong>线程2</strong>来获得锁对象,会<strong>查找对象头中记录的偏向锁偏向的线程ID</strong>(线程1),如果说还是要继续持有这个锁对象,暂停线程1,撤销偏向锁,升级为轻量级锁(如果线程1不再使用该锁对象,那么将锁对象状态设为无锁状态,重新偏向新的线程)。如果<strong>线程2</strong>获取轻量级锁时使用CAS获取失败,那么线程2会<strong>通过自旋来获得锁</strong>。如果这个时候<strong>线程3</strong>也来获取锁对象,线程2还在<strong>自选等待</strong>,没获得到锁,那么<strong>这个时候轻量级锁就会膨胀为重量级锁。重量级锁把除了拥有锁的线程都阻塞,防止CPU空转。</strong></p>
<h3 id="73reentrantlock优缺点">7.3、ReentrantLock优缺点?</h3>
<p><img src="https://cdn.jsdelivr.net/gh/recordnote/cdn/img/image-20230710172118891.png" alt="image-20230710172118891"></p>
<h3 id="74底层实现aqscas">7.4、底层实现?(AQS、CAS) </h3>
<p>**CAS:**CAS叫做CompareAndSwap,比较并交换,如果主内存的值和期望值一样,那就会进行修改,否则会一直重试。它功能是判断内存某个位置的值是否是预期值,如果是则更改为新值,这个过程是原子的。(<strong>CAS是一条CPU的原子指令</strong>,不会造成数据不一致问题。)</p>
<p><strong>AQS:<strong>AQS全称为AbstractQueuedSychronizer,翻译过来应该是</strong>抽象队列同步器</strong>。AQS是整个Java并发包的核心,AQS是一个用来<strong>构建锁和同步器的框架</strong>,比如ReentrantLock,Semaphore,ReentrantReadWriteLock,SynchronousQueue,FutureTask等等皆是基于AQS的。<strong>AQS核心思想是,如果被请求的共享资源空闲,则将当前请求资源的线程设置为有效的工作线程,并且将共享资源设置为锁定状态。如果被请求的共享资源被占用,那么就需要一套线程阻塞等待以及被唤醒时锁分配的机制,这个机制AQS是用CLH(虚拟的双向队列)队列锁实现的,即将暂时获取不到锁的线程加入到队列中。</strong></p>
<p>AQS定义了两种资源获取方式:独占(只有一个线程能访问执行,又根据是否按队列的顺序分为公平锁和非公平锁,如ReentrantLock) 和共享(多个线程可同时访问执行,如Semaphore/CountDownLatch,Semaphore、CountDownLatCh、 CyclicBarrier )。</p>
<p><strong>补充:<code>Semaphore</code>(信号量)-允许多个线程同时访问某一个共享资源、</strong> <code>CountDownLatch </code>(倒计时器)让某一个线程等待直到倒计时结束,再开始执行</p>
<p>AQS底层<strong>使用了模板方法模式</strong>, <strong>自定义同步器</strong>在实现时只<strong>需要实现共享资源 state 的获取与释放方式</strong>即可,至于具体线程等待队列的维护(如获取资源失败入队/唤醒出队等),AQS已经在上层已经帮我们实现好了。</p>
<h3 id="75cas会存在什么问题如何避免">7.5、CAS会存在什么问题?如何避免?</h3>
<p>存在ABA问题 :ABA的问题指的是在<strong>CAS更新的过程</strong>中,当读取到的值是A,然后准备赋值的时候仍然是A,但是实际上<strong>有可能A的值被改成了B,然后又被改回了A</strong>,这个CAS更新的漏洞就叫做ABA。只是ABA的问题大部分场景下都不影响并发的最终效果。</p>
<p>解决方法:使用时间戳 <code>AtomicStampedReference</code> , 这会维护一个版本号 stamp,在CAS操作过程中,不仅要比较当前值,还要比较版本号。</p>
<p>其他问题:a、<strong>循环时间长开销大</strong>:自旋CAS的方式如果长时间不成功,会给CPU带来很大的开销。 b、<strong>只能保证一个共享变量的原子操作</strong>:只对一个共享变量操作可以保证原子性,但是多个则不行。</p>
<h3 id="76公平锁和非公平锁在aqs上是如何实现的synchonized是公平锁还是非公平锁">7.6、公平锁和非公平锁在AQS上是如何实现的?Synchonized是公平锁还是非公平锁?</h3>
<p>AQS,抽线队列同步器(abstractQueuedSynchronizer),是可以实现锁和同步器的框架,内部实现的关键是维护了一个先进先出的队列已经state状态变量,先进先出队列存储的载体是Node节点,节点记录着当前状态值、是独占还是共享模式等信息,AQS定义了模板,具体实现由子类完成。</p>
<p>**公平锁:**公平锁就是把竞争的线程放在一个先进先出的队列上,如果持有锁的线程执行完了,唤醒队列的下一个线程去获得锁。</p>
<p>**非公平锁:**获得锁的顺序不会按照线程申请的先后顺序,后到的线程可能比临界区的线程获得锁,实现:线程先尝试能不能获得锁,如果获得不到锁,就把线程放到队列里面,与公平锁的区别是它会先尝试获得锁,而公平锁是直接放进队列,等待唤醒。(Synchonized是非公平锁)</p>
<h3 id="77-读写锁是怎么实现的也是基于aqs的">7.7、 读写锁是怎么实现的?(也是基于AQS的)</h3>
<p>基于AQS,Java读写锁用state的高16位表示读锁的线程数,低16位表示写锁的重入数。其中读锁类中的Sync实现共享获取、释放锁方法,写锁类中Sync实现互斥获取、释放锁方法。(当读取数据时用读锁,当没有线程获取到写锁,多个线程可同时获取到读锁;当没有线程获取到读锁时,可以获取到写锁,最多只有一个线程能获取到写锁)</p>
<h2 id="8线程池的理解">8、线程池的理解</h2>
<h3 id="81线程池创建的4中方法">8.1、线程池创建的4中方法?</h3>
<ul>
<li>继承Thread类</li>
<li>实现Runnable接口</li>
<li>实现callable接口通过FutureTask包装器来创建Thread线程</li>
<li>通过线程池创建线程,使用线程池接口ExecutorService结合Callable、Future实现有返回结果的多线程。</li>
</ul>
<h3 id="82任务加入的线程池的流程">8.2、任务加入的线程池的流程?</h3>
<p>流程:</p>
<p>1)当我们提交任务,线程池会根据核心线程数(corePoolSize)大小创建若干任务数量线程执行任务</p>
<p>2)当任务数量大于核心线程数(corePoolSize)数量,后续的任务将会进入阻塞队列阻塞排队。</p>
<p>3)当阻塞队列也满了之后,那会继续创建最大线程数减去核心线程数(maximumPoolSize - corePoolSize)个数量线程来执行任务,如果任务处理完成,(maximumPoolSize - corePoolSize)额外创建的线程在达到活跃时间(keepAliveTime)之后就自动销毁了。</p>
<p>4)如果达到最大线程数maximumPoolSize,<strong>阻塞队列还是满的状态</strong>,那会根据不同的拒绝策略对应处理。</p>
<h3 id="83线程池的7个参数拒绝策略">8.3、线程池的7个参数?拒绝策略?</h3>
<p><strong>核心参数:</strong></p>
<p>1)最大线程数maximumPoolSize</p>
<p>2)核心线程数corePoolSize</p>
<p>3)活跃时间keepAliveTime</p>
<p>4)阻塞队列workQueue</p>
<p>5)拒绝策略RejectedExecutionHandler</p>
<p>6)时间单位unit</p>
<p>7)线程工厂threadFactory</p>
<p><strong>四种拒绝策略:</strong></p>
<p>1)AbortPolicy:直接丢弃任务,抛出异常,真是默认策略。</p>
<p>2)CallerRunsPolicy:<strong>只用调用者所在的线程来处理任务</strong>。</p>
<p>3)DiscardOldestPolicy:<strong>丢弃等待队列中最旧的任务</strong>,并执行当前任务。</p>
<p>4)DiscardPolicy:直接丢弃任务,不抛出异常。</p>
<p><strong>补充</strong>:<strong>执行 execute()方法和 submit()方法的区别:</strong></p>
<p><strong>execute() 方法</strong>用于提交不需要返回值的任务,所以无法判断任务是否被线程池所执行成功;
<strong>submit() 方法</strong>用于提交需要返回值的任务。线程池会返回一个 Future 类型对象,通过这个 Future对象可以判断任务是否执行成功</p>
<h3 id="84线程池中如何拿到线程的执行结果">8.4、线程池中如何拿到线程的执行结果?</h3>
<p>执行任务的时候用submit() 方法,线程池会返回一个 Future 类型对象,通过这个 Future对象的 get() 方法获得返回值(get()方法会阻塞当前任务直到任务完成)。</p>
<h2 id="9threadlocal了解">9、ThreadLocal了解?</h2>
<p>本地线程,每个线程都创建一个副本,那么在线程之间访问内部副本变量就行了,做到了线程之间互相隔离,可以实现每个线程自己专属本地变量副本,可以避免线程安全问题。</p>
<p>**补充:乐观锁,悲观锁:**a、乐观锁,每次去拿数据的时候都认为别人不会修改,所以不会上锁。实现机制用CAS。 b、悲观锁,每次去拿数据的时候都认为别人会修改,例如synchronized。</p>
</article>
</section>
<article class="ui segment utterances-comments" data-html2canvas-ignore>
<script
src="https://utteranc.es/client.js"
repo="recordnote/recordnote.github.io"
issue-term="og:title"
theme="github-light"
crossorigin="anonymous"
async>
</script>
</article>
</div>
</div>
<footer class="ui basic center aligned segment" style="background-color: transparent;">
<p>© 2019 - 2026 Lin 的博客</p>
<p>Powered by <a href="https://gohugo.io/" target="_blank">Hugo</a> with theme <a href="https://github.com/g1eny0ung/hugo-theme-dream" target="_blank">Dream</a>.</p>
</footer>
</div>
</section>
<section class="back">
<div class="dream-max-width">
<header class="ui basic very padded segment dream-header">
<div class="ui small circular image">
<img src="/me/yy.jpg" alt="avatar" />
</div>
<div class="content">
<h1 class="ui medium header">
Lin 的博客
<span class="sub header">A merry heart goes all the way.</span>
</h1>
<nav class="ui horizontal list" aria-label="博客导航">
<a class="item" href="/posts" aria-label="归档">
<i class="archive icon" aria-hidden="true"></i>
</a>
<a class="item" href="/categories" aria-label="所有分类">
<i class="th list icon" aria-hidden="true"></i>
</a>
<a class="item" href="/tags" aria-label="所有标签">
<i class="tags icon" aria-hidden="true"></i>
</a>
</nav>
<nav class="dream-topic-nav" aria-label="文章主题">
<div class="dream-tags dream-tags-primary">
<a class="ui label" href="/tags/agent/">Agent</a>
<a class="ui label" href="/tags/ai%E5%BA%94%E7%94%A8/">AI应用</a>
<a class="ui label" href="/tags/java/">Java</a>
<a class="ui label" href="/tags/%E6%9E%B6%E6%9E%84%E8%AE%BE%E8%AE%A1/">架构设计</a>
<a class="ui label" href="/tags/rag/">RAG</a>
<a class="ui label" href="/tags/%E5%BE%AE%E6%9C%8D%E5%8A%A1/">微服务</a>
</div>
<details class="dream-tags-more">
<summary>更多主题 <span>(7)</span></summary>
<div class="dream-tags dream-tags-secondary">
<a class="ui label" href="/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/">数据库</a>
<a class="ui label" href="/tags/%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/">消息队列</a>
<a class="ui label" href="/tags/%E5%AE%89%E5%85%A8/">安全</a>
<a class="ui label" href="/tags/%E7%94%9F%E6%B4%BB%E9%9A%8F%E7%AC%94/">生活随笔</a>
<a class="ui label" href="/tags/%E7%AE%97%E6%B3%95%E4%B8%8E%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/">算法与数据结构</a>
<a class="ui label" href="/tags/%E5%89%8D%E7%AB%AF/">前端</a>
<a class="ui label" href="/tags/%E8%BF%90%E7%BB%B4/">运维</a>
</div>
</details>
</nav>
</div>
</header>
<div class="ui relaxed grid dream-grid dream-back">
<div class="sixteen wide mobile eight wide tablet four wide computer column dream-column">
<article class="ui segment markdown-body">
<div class="ui medium header">关于我</div>
<p>Lin 的 ❤️ 博客</p>
<p>技术专题:<a href="/agent-engineering/overview/">Java Agent 工程化:从知识库问答到可靠业务执行</a>。围绕 RAG、工具治理、任务恢复与 Java 平台架构整理设计思路和验证方法。</p>
<p>记录一些 🌈 生活上,技术上的事</p>
<ul>
<li><strong>🛠️ 技术阵地:</strong> 深耕 Java 开发 ,目前向 AI 应用领域探索与拓展。这里主要记录我从后端架构到 AI 赋能的进阶之路、技术思考以及日常的 debug 血泪史。始终致力于写出优雅且没有 bug 的代码(尽量)。</li>
<li><strong>🌈 生活侧写:</strong> 偶尔脱下极客的外衣,我也会在这里分享生活中的灵光一现。不管是好用的效率工具,还是周末的一场骑行,都是构成我真实生活的一部分。</li>
</ul>
</article>
</div>
<div class="sixteen wide mobile eight wide tablet four wide computer column dream-column">
<article class="ui segment">
<div class="ui medium header">社交链接</div>
<nav class="ui secondary menu dream-menu dream-socials">
<div class="item">
<a href="/index.xml">
<i class="large rss square icon" title="RSS"></i>
</a>
</div>
<div class="item">
<a href="mailto:zhjlynn@foxmail.com">
<i class="large mail icon" title="Email"></i>
</a>
</div>
<div class="item">
<a href="https://twitter.com/Lin" target="_blank">
<i class="large twitter icon" title="Twitter"></i>
</a>
</div>
<div class="item">
<a href="https://facebook.com/Lin" target="_blank">
<i class="large facebook icon" title="Facebook"></i>
</a>
</div>
<div class="item">
<a href="https://instagram.com/Lin" target="_blank">
<i class="large instagram icon" title="Instagram"></i>
</a>
</div>
<div class="item">
<a href="https://www.linkedin.com/in/Lin" target="_blank">
<i class="large linkedin icon" title="Linkedin"></i>
</a>
</div>
<div class="item">
<a href="https://github.com/Lin" target="_blank">
<i class="large github icon" title="GitHub"></i>
</a>
</div>
<div class="item">
<a href="https://www.stackoverflow.com/users/Lin" target="_blank">
<i class="large stack overflow icon" title="StackOverflow"></i>
</a>
</div>
</nav>
</article>
</div>
<div class="sixteen wide mobile eight wide tablet four wide computer column dream-column">
<article class="ui segment">
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img alt="知识共享许可协议" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png" /></a><br />本作品采用<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/">知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议</a>进行许可。<br /><br />背景使用了 <a href="https://www.pexels.com/zh-cn/" target="_blank">Pexels</a> 上 <a href="https://www.pexels.com/zh-cn/Ungaro" target="_blank">Francesco Ungaro</a> 拍摄的<a href="https://www.pexels.com/zh-cn/photo/1454794/" target="_blank">图片</a>。
</article>
</div>
</div>
</div>
</section>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0"></script>
<script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script>
<div class="ui segment" id="dream-search">
<div class="ui search">
<div class="ui transparent input">
<input class="prompt" type="text" placeholder="搜索" />
</div>
<div class="results"></div>
</div>
</div>
<script>
$(document).ready(function () {
$.getJSON('https:\/\/recordnote.github.io/index.json', function (data) {
$('.ui.search').search({
source: data,
searchFields: ['title'],
showNoResults: false,
})
})
})
</script>
<script src="/js/search.js"></script>
<script>
window.background = "#fff"
window.defaultDark = null
window.backgroundDark = "#333"
window.backgroundImageDark = "/me/background1.jpg"
window.darkNav = null
window.maxTags = 6
window.hasTwitterEmbed = null
window.fixedNav = true
if (window.hasTwitterEmbed) {
window.twttr = (function (d, s, id) {
var js,
fjs = d.getElementsByTagName(s)[0],
t = window.twttr || {}
if (d.getElementById(id)) return t
js = d.createElement(s)
js.id = id
js.src = 'https://platform.twitter.com/widgets.js'
fjs.parentNode.insertBefore(js, fjs)
t._e = []
t.ready = function (f) {
t._e.push(f)
}
return t
})(document, 'script', 'twitter-wjs')
}
</script>
<script src="https://cdn.jsdelivr.net/npm/overlayscrollbars@1.13.1/js/jquery.overlayScrollbars.min.js"></script>
<script src="/js/header.js"></script>
<script src="/js/main.js"></script>
<script src="/js/theme.js"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@1.26.0"></script>
<script>
format()
function format() {
$('span[data-format="luxon"]').each(function () {
var date = $(this).text()
$(this).text(luxon.DateTime.fromISO(date, { locale: "zh" }).toFormat("yyyy年MM月dd日"))
})
}
</script>
<script src="/js/scrollToTop.js"></script>
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release/build/highlight.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release/build/languages/clojure.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release/build/languages/ocaml.min.js"></script>
<script>
hljs.highlightAll()
setHighlightTheme()
function setHighlightTheme() {
var isDark = localStore.getItem('hugo-theme-dream-is-dark')
isDark = isDark ? isDark : window.defaultDark ? 'y' : isDark
var lightTheme = "tomorrow"
var darkTheme = "tomorrow-night"
var theme = isDark === 'y' ? darkTheme : lightTheme
$('link[data-highlight]').attr('href', 'https://cdn.jsdelivr.net/gh/highlightjs/cdn-release/build/styles/' + theme + '.min.css')
$('pre').css('background', isDark === 'y' ? '#333' : '')
}
</script>
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.0.0-rc.1"></script>
<script src="/js/post.js" defer></script>
<script type="application/javascript">
var doNotTrack = false;
if (!doNotTrack) {
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-98295641-1', 'auto');
ga('send', 'pageview');
}
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
</body>
</html>