File tree Expand file tree Collapse file tree 3 files changed +102
-1
lines changed
out/production/thread/com/cpucode/java
thread/src/com/cpucode/java Expand file tree Collapse file tree 3 files changed +102
-1
lines changed Original file line number Diff line number Diff line change 6969
7070- [x] [ Deadlock__ 死锁] ( deadlock/Deadlock.java )
7171
72-
7372- [ 返回文件目录] ( #文件目录 )
7473
7574---------------
7675
76+ ## [ 等待唤醒线程] ( wait/notify )
77+
78+ - [x] [ WaitNotify__ 等待唤醒线程] ( wait/notify/WaitNotify.java )
7779
80+ - [ 返回文件目录] ( #文件目录 )
81+
82+ ---------------
7883
7984
8085- [x] [ thread1__ 创建新线程] ( thread/thread2.java )
Original file line number Diff line number Diff line change 7373
7474---------------
7575
76+ ## [ 等待唤醒线程] ( wait/notify )
7677
78+ - [x] [ WaitNotify__ 等待唤醒线程] ( wait/notify/WaitNotify.java )
79+
80+ - [ 返回文件目录] ( #文件目录 )
81+
82+ ---------------
7783
7884
7985- [x] [ thread1__ 创建新线程] ( thread/thread2.java )
Original file line number Diff line number Diff line change 1+ package com .cpucode .java .wait .notify ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .LinkedList ;
5+ import java .util .List ;
6+ import java .util .Queue ;
7+
8+ /**
9+ * @author : cpucode
10+ * @date : 2021/2/9
11+ * @time : 17:24
12+ * @github : https://github.com/CPU-Code
13+ * @csdn : https://blog.csdn.net/qq_44226094
14+ */
15+ public class WaitNotify {
16+ @ SuppressWarnings ("AlibabaAvoidManuallyCreateThread" )
17+ public static void main (String [] args ) throws InterruptedException {
18+ TaskQueue q = new TaskQueue ();
19+ List <Thread > ts = new ArrayList <Thread >();
20+ int num = 5 ;
21+ int num1 = 10 ;
22+
23+ for (int i = 0 ; i < num ; i ++) {
24+ //noinspection AlibabaAvoidManuallyCreateThread
25+ Thread t = new Thread (){
26+ @ Override
27+ public void run (){
28+ // 执行task:
29+ while (true ){
30+ try {
31+ String s = q .getTask ();
32+
33+ System .out .println ("execute task : " + s );
34+ } catch (InterruptedException e ){
35+ return ;
36+ }
37+ }
38+ }
39+ };
40+
41+ t .start ();
42+ ts .add (t );
43+ }
44+
45+ Thread add = new Thread (() ->{
46+ for (int i = 0 ; i < num1 ; i ++) {
47+ // 放入task:
48+ String s = "t -" + Math .random ();
49+
50+ System .out .println ("add task:" + s );
51+
52+ q .addTask (s );
53+
54+ try {
55+ Thread .sleep (100 );
56+ }catch (InterruptedException e ){
57+ e .printStackTrace ();
58+ }
59+ }
60+ });
61+
62+ add .start ();
63+ add .join ();
64+
65+ Thread .sleep (100 );
66+
67+ for (Thread t : ts ){
68+ t .interrupt ();
69+ }
70+ }
71+ }
72+
73+ class TaskQueue {
74+ Queue <String > queue = new LinkedList <>();
75+
76+ public synchronized void addTask (String s ){
77+ this .queue .add (s );
78+ //唤醒所有当前正在this锁等待的线程
79+ this .notifyAll ();
80+ }
81+
82+ public synchronized String getTask () throws InterruptedException {
83+ while (queue .isEmpty ()){
84+ //等待
85+ this .wait ();
86+ }
87+
88+ return queue .remove ();
89+ }
90+ }
You can’t perform that action at this time.
0 commit comments