-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchapter.java.thread.xml
More file actions
809 lines (698 loc) · 21.6 KB
/
chapter.java.thread.xml
File metadata and controls
809 lines (698 loc) · 21.6 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
<?xml version="1.0" encoding="UTF-8"?>
<chapter id="index"><?dbhtml dir="thread" ?>
<title>Java 线程</title>
<para>java.lang.Thread</para>
<section>
<title>多线程 Lambda 表达式</title>
<programlisting>
<![CDATA[
new Thread(new Runnable() {
@Override
public void run() {
getPermission();
}
}).start();
]]>
</programlisting>
<programlisting>
<![CDATA[
new Thread(() -> {
Thread.sleep(millis);
});
]]>
</programlisting>
<programlisting>
<![CDATA[
new Thread(() -> System.out.println("多线程")).start();
]]>
</programlisting>
</section>
<section>
<title>实现异步执行</title>
<programlisting>
<![CDATA[
public void testThread() throws Exception {
try {
Thread sendmail = new Thread(new Runnable() {
@Override
public void run() {
// Sendmail
log.info("Sendmail OK");
}
});
sendmail.setName("sendmail");
sendmail.start();
} catch (Exception e) {
e.printStackTrace();
}
}
]]>
</programlisting>
<para></para>
</section>
<section id="Thread">
<title>继承 Thread 类实现多线程</title>
<programlisting>
<![CDATA[
package cn.netkiller.ipo.test;
public class MyThread extends Thread {
private String name;
public MyThread(String name) {
super();
this.name = name;
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Thread:" + this.name + ",i=" + i);
}
}
public static void main(String[] args) {
MyThread mt1 = new MyThread("A");
MyThread mt2 = new MyThread("B");
mt1.start();
mt2.start();
}
}
]]>
</programlisting>
<section id="thread.getName">
<title>设置线程名称</title>
<para></para>
<programlisting>
<![CDATA[
public static void setThreadName1() {
new Thread("thread-name-1") {
public void run() {
try {
Thread.sleep(1000 * 15);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("threadName1: " + this.getName());
}
}.start();
}
public static void setThreadName2() {
new Thread() {
@SneakyThrows
public void run() {
this.setName("thread-name-2");
Thread.sleep(1000 * 15);
System.out.println("threadName2: " + this.getName());
}
}.start();
}
public static void setThreadName3() {
Thread thread = new Thread() {
public void run() {
try {
Thread.sleep(1000 * 15);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("threadName3: " + this.getName());
}
};
thread.setName("thread-name-3");
thread.start();
}
public static void setThreadName4() {
new Thread("测试线程-1") {
public void run() {
try {
Thread.sleep(1000 * 15);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("threadName1: " + this.getName());
}
}.start();
}
]]>
</programlisting>
<para></para>
<programlisting>
<![CDATA[
public class MyThread extends Thread {
public MyThread(){
}
public MyThread(String name){
super(name);
}
@Override
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
public class DemoThreadName {
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.setName("景峰");
mt.start();
new MyThread("netkiller").start();
}
}
]]>
</programlisting>
</section>
<section id="thread.isAlive">
<title>判断线程是否存活</title>
<programlisting>
<![CDATA[
package cn.netkiller.test;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Data
@Slf4j
public class Test {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000); // 模拟任务执行
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("启动前是否存活: " + thread.isAlive()); // false (NEW)
thread.start();
System.out.println("启动后是否存活: " + thread.isAlive()); // true (RUNNABLE)
Thread.sleep(500);
System.out.println("运行中是否存活: " + thread.isAlive()); // true (TIMED_WAITING)
thread.join(); // 等待线程结束
System.out.println("结束后是否存活: " + thread.isAlive()); // false (TERMINATED)
Thread thread1 = new Thread();
System.out.println("启动前是否存活: " + thread1.isAlive()); // false
}
}
]]>
</programlisting>
</section>
<section id="thread.getState">
<title>获取线程状态</title>
<programlisting>
<![CDATA[
package cn.netkiller.test;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Data
@Slf4j
public class Test {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000); // TIMED_WAITING
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println(thread.getState()); // NEW (before start)
thread.start();
System.out.println(thread.getState()); // RUNNABLE (after start)
Thread.sleep(100);
System.out.println(thread.getState()); // TIMED_WAITING (sleeping)
thread.join();
System.out.println(thread.getState()); // TERMINATED (after completion)
}
}
]]>
</programlisting>
</section>
</section>
<section id="Runnable">
<title>实现 Runnable 接口</title>
<programlisting>
<![CDATA[
package cn.netkiller.ipo.test;
public class MyRunnable implements Runnable {
private String name;
public MyRunnable(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Thread:" + this.name + ",i=" + i);
}
}
public static void main(String[] args) {
MyRunnable mr1 = new MyRunnable("A");
MyRunnable mr2 = new MyRunnable("B");
new Thread(mr1).start();
new Thread(mr2).start();
new Thread(new MyRunnable("C")).start();
}
}
]]>
</programlisting>
</section>
<section id="synchronized">
<title>线程同步</title>
<programlisting>
<![CDATA[
package cn.netkiller.thread;
public class SynchronizedThread extends Thread {
private int count = 0;
@Override
public /*synchronized*/ void run() {
count++;
System.out.println(Thread.currentThread().getName() + " count:" + count);
}
public static void main(String[] args) {
SynchronizedThread myThread = new SynchronizedThread();
Thread thread1 = new Thread(myThread, "thread1");
Thread thread2 = new Thread(myThread, "thread2");
Thread thread3 = new Thread(myThread, "thread3");
Thread thread4 = new Thread(myThread, "thread4");
Thread thread5 = new Thread(myThread, "thread5");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}
]]>
</programlisting>
<para>线程运行不分先后</para>
<screen>
<![CDATA[
thread2 count:3
thread4 count:4
thread1 count:3
thread3 count:3
thread5 count:5
]]>
</screen>
<programlisting>
<![CDATA[
package cn.netkiller.thread;
public class SynchronizedThread extends Thread {
private int count = 0;
@Override
public synchronized void run() {
count++;
System.out.println(Thread.currentThread().getName() + " count:" + count);
}
public static void main(String[] args) {
SynchronizedThread myThread = new SynchronizedThread();
Thread thread1 = new Thread(myThread, "thread1");
Thread thread2 = new Thread(myThread, "thread2");
Thread thread3 = new Thread(myThread, "thread3");
Thread thread4 = new Thread(myThread, "thread4");
Thread thread5 = new Thread(myThread, "thread5");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
}
}
]]>
</programlisting>
<screen>
<![CDATA[
thread1 count:1
thread5 count:2
thread4 count:3
thread2 count:4
thread3 count:5
]]>
</screen>
<programlisting>
<![CDATA[
package cn.netkiller.thread;
public class MultiThread {
private static int count = 0;
public synchronized void add() {
count++;
System.out.println(Thread.currentThread().getName() + " count:" + count);
}
public static void main(String[] args) throws InterruptedException {
final MultiThread multiThread1 = new MultiThread();
final MultiThread multiThread2 = new MultiThread();
final MultiThread multiThread3 = new MultiThread();
final MultiThread multiThread4 = new MultiThread();
final MultiThread multiThread5 = new MultiThread();
new Thread(new Runnable() {
public void run() {
multiThread1.add();
}
}).start();
new Thread(new Runnable() {
public void run() {
multiThread2.add();
}
}).start();
new Thread(new Runnable() {
public void run() {
multiThread3.add();
}
}).start();
new Thread(new Runnable() {
public void run() {
multiThread4.add();
}
}).start();
new Thread(new Runnable() {
public void run() {
multiThread5.add();
}
}).start();
}
}
]]>
</programlisting>
</section>
<section id="ThreadLocal">
<title>ThreadLocal</title>
<programlisting>
<![CDATA[
public static void threadLocal() {
ThreadLocal<String> local = new ThreadLocal<>();
IntStream.range(0, 10).forEach(i -> new Thread(() -> {
local.set(Thread.currentThread().getName() + ":" + i);
System.out.println("线程:" + Thread.currentThread().getName() + ",local:" + local.get());
}).start());
}
]]>
</programlisting>
<programlisting>
<![CDATA[
package cn.netkiller.thread;
public class ThreadLocaTest {
private static ThreadLocal<String> local = new ThreadLocal<String>();
public static void main(String[] args) throws InterruptedException {
new Thread(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName() + ":" + local.get());
ThreadLocaTest.local.set("thread_A");
System.out.println(Thread.currentThread().getName() + ":" + local.get());
}
}, "A").start();
Thread.sleep(1000);
new Thread(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName() + ":" + local.get());
ThreadLocaTest.local.set("thread_B");
System.out.println(Thread.currentThread().getName() + ":" + local.get());
local.remove();
System.out.println("remove: " + local.get());
}
}, "B").start();
}
}
]]>
</programlisting>
<programlisting>
<![CDATA[
package cn.netkiller.test;
public class Test {
public static void main(String[] args) {
System.out.println(Thread.currentThread());
try (var ctx = new UserContext("Bob")) {
// 可任意调用UserContext.currentUser():
String currentUser = UserContext.currentUser();
System.out.println(currentUser);
} // 在此自动调用UserContext.close()方法释放ThreadLocal关联对象
}
public static class UserContext implements AutoCloseable {
static final ThreadLocal<String> ctx = new ThreadLocal<>();
public UserContext(String user) {
ctx.set(user);
}
public static String currentUser() {
return ctx.get();
}
@Override
public void close() {
ctx.remove();
}
}
}
]]>
</programlisting>
</section>
<section id="ScopedValue">
<title>ScopedValue</title>
<para>Scoped Value 允许声明一个只能在当前范围(如代码块或方法调用栈)内访问的变量。这个范围可以包含多个线程,但这些变量只能被当前范围内的代码读取,无法被其他范围内的代码读取或修改。因此,Scoped Value 是不可变的,并且可以安全地在线程之间共享。</para>
<programlisting>
<![CDATA[
import java.lang.Scope;
import java.lang.ScopedValue;
public class ScopedValueDemo {
private static ScopedValue<String> stringScopedValue = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.runWhere(stringScopedValue, "Hello, Scoped Value!", () -> {
System.out.println(stringScopedValue.get());
anotherMethod();
});
}
public static void anotherMethod() {
System.out.println(stringScopedValue.get());
}
}
]]>
</programlisting>
</section>
<section id="ThreadLocalMap">
<title>ThreadLocalMap</title>
</section>
<section id="InheritableThreadLocal">
<title>InheritableThreadLocal</title>
<programlisting>
<![CDATA[
public static void inheritableThreadLocal() {
InheritableThreadLocal threadLocal = new InheritableThreadLocal();
IntStream.range(0, 10).forEach(i -> {
//每个线程的序列号,希望在子线程中能够拿到
threadLocal.set(i);
//这里来了一个子线程,我们希望可以访问上面的threadLocal
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + ":" + threadLocal.get());
}).start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
]]>
</programlisting>
</section>
<section id="Thread.setDaemon">
<title>守护线程</title>
<programlisting>
<![CDATA[
package cn.netkiller.test;
public class Test {
public static void main(String[] args) {
System.out.println(Thread.currentThread());
Thread t = new Thread(() -> {
Thread.currentThread().setName("netkiller");
System.out.println(Thread.currentThread().getName() + ": running...");
while (true) {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread() + " - " + System.currentTimeMillis());
} catch (InterruptedException e) {
System.out.println(e.getMessage());
break;
}
}
});
t.setDaemon(true);//设置为守护线程【表示守护主线程,随主线程结束而结束】
t.start();
while (t.isAlive()) {
try {
ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
int activeCount = currentGroup.activeCount();
Thread[] threads = new Thread[activeCount];
currentGroup.enumerate(threads);
for (Thread thread : threads) {
System.out.println("线程号:" + thread.getId() + " = " + thread.getName() + " 线程状态:" + thread.getState());
}
Thread.sleep(5000);
t.interrupt();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
]]>
</programlisting>
</section>
<section id="Thread.wait()">
<title>线程等待与线程通知</title>
<para>wait() 与 notify() 的用法</para>
<para>A 线程等待, 直到 B 线程发出通知</para>
<programlisting>
<![CDATA[
package cn.netkiller.test;
public class Test {
static Object object = new Object();
public static void main(String[] args) {
Test test = new Test();
new Thread(() -> {
synchronized (object) {
System.out.println("开始线程 A");
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("结束线程 A");
}
}, "线程 A").start();
new Thread(() -> {
try {
Thread.sleep(500L);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object) {
System.out.println("开始线程 B");
object.notify();
System.out.println("结束线程 B");
}
}, "线程 B").start();
}
}
]]>
</programlisting>
<section>
<title>通知所有线程</title>
<para>每次发送通知,只能通知到其中一个线程,多个线程必须多次发出通知。</para>
<programlisting>
<![CDATA[
package cn.netkiller.test;
public class Test {
static Object object = new Object();
public static void main(String[] args) {
Test test = new Test();
new Thread(() -> {
synchronized (object) {
System.out.println("开始线程 A");
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("结束线程 A");
}
}, "线程 A").start();
new Thread(() -> {
try {
Thread.sleep(500L);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object) {
System.out.println("开始线程 B");
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("结束线程 B");
}
}, "线程 B").start();
new Thread(() -> {
try {
Thread.sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object) {
System.out.println("开始通知线程 C");
object.notify();
object.notify();
System.out.println("结束通知线程 C");
}
}, "线程 C").start();
}
}
]]>
</programlisting>
<para>notifyAll() 一次通知所有线程</para>
<programlisting>
<![CDATA[
new Thread(() -> {
try {
Thread.sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object) {
System.out.println("开始通知线程 C");
object.notifyAll();
System.out.println("结束通知线程 C");
}
}, "线程 C").start();
]]>
</programlisting>
</section>
<section>
<title>携带消息</title>
<programlisting>
<![CDATA[
package cn.netkiller.test;
import lombok.Data;
public class Test {
private static final Message object = new Message();
public static void main(String[] args) {
Test test = new Test();
new Thread(() -> {
synchronized (object) {
System.out.println("开始线程 A");
try {
object.wait();
System.out.println(Thread.currentThread().getName() + ": " + object.getText());
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("结束线程 A");
}
}, "线程 A").start();
new Thread(() -> {
try {
Thread.sleep(500L);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object) {
System.out.println("开始线程 B");
try {
object.wait();
System.out.println(Thread.currentThread().getName() + ": " + object.getText());
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("结束线程 B");
}
}, "线程 B").start();
new Thread(() -> {
try {
Thread.sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object) {
System.out.println("开始通知线程 C");
object.setText("https:/www.netkiller.cn");
object.notifyAll();
System.out.println("结束通知线程 C");
}
}, "线程 C").start();
}
@Data
public static class Message {
private String text;
}
}
]]>
</programlisting>
</section>
</section>
</chapter>