10
10
*/
11
11
public class TwoThreadWaitNotify {
12
12
13
- private int start = 1 ;
13
+ private int start = 1 ;
14
14
15
- private boolean flag = false ;
15
+ private boolean flag = false ;
16
16
17
17
public static void main (String [] args ) {
18
- TwoThread twoThread = new TwoThread ();
18
+ TwoThreadWaitNotify twoThread = new TwoThreadWaitNotify ();
19
19
20
- Thread t1 = new Thread (new TwoThread . OuNum (twoThread ));
20
+ Thread t1 = new Thread (new OuNum (twoThread ));
21
21
t1 .setName ("t1" );
22
22
23
23
24
- Thread t2 = new Thread (new TwoThread . JiNum (twoThread ));
24
+ Thread t2 = new Thread (new JiNum (twoThread ));
25
25
t2 .setName ("t2" );
26
26
27
27
t1 .start ();
@@ -40,13 +40,18 @@ public OuNum(TwoThreadWaitNotify number) {
40
40
41
41
@ Override
42
42
public void run () {
43
- synchronized (TwoThreadWaitNotify .class ){
44
- while (number .start <= 100 ){
45
- if (number .flag ){
46
- System .out .println (Thread .currentThread ().getName () + "+-+" + number .start );
47
- number .start ++ ;
48
43
49
- number .flag = false ;
44
+ while (number .start <= 100 ) {
45
+ synchronized (TwoThreadWaitNotify .class ) {
46
+ System .out .println ("偶数线程抢到锁了" );
47
+ if (number .flag ) {
48
+ System .out .println (Thread .currentThread ().getName () + "+-+偶数" + number .start );
49
+ number .start ++;
50
+
51
+ number .flag = false ;
52
+ TwoThreadWaitNotify .class .notify ();
53
+
54
+ }else {
50
55
try {
51
56
TwoThreadWaitNotify .class .wait ();
52
57
} catch (InterruptedException e ) {
@@ -63,7 +68,7 @@ public void run() {
63
68
/**
64
69
* 奇数线程
65
70
*/
66
- public static class JiNum implements Runnable {
71
+ public static class JiNum implements Runnable {
67
72
private TwoThreadWaitNotify number ;
68
73
69
74
public JiNum (TwoThreadWaitNotify number ) {
@@ -72,15 +77,22 @@ public JiNum(TwoThreadWaitNotify number) {
72
77
73
78
@ Override
74
79
public void run () {
75
- synchronized (TwoThreadWaitNotify .class ){
76
- while (number .start <= 100 ){
77
- if (!number .flag ){
78
- System .out .println (Thread .currentThread ().getName () + "+-+" + number .start );
79
- number .start ++ ;
80
+ while (number .start <= 100 ) {
81
+ synchronized (TwoThreadWaitNotify .class ) {
82
+ System .out .println ("奇数线程抢到锁了" );
83
+ if (!number .flag ) {
84
+ System .out .println (Thread .currentThread ().getName () + "+-+奇数" + number .start );
85
+ number .start ++;
80
86
81
- number .flag = true ;
87
+ number .flag = true ;
82
88
83
89
TwoThreadWaitNotify .class .notify ();
90
+ }else {
91
+ try {
92
+ TwoThreadWaitNotify .class .wait ();
93
+ } catch (InterruptedException e ) {
94
+ e .printStackTrace ();
95
+ }
84
96
}
85
97
}
86
98
}
0 commit comments