1010 */
1111public class TwoThreadWaitNotify {
1212
13- private int start = 1 ;
13+ private int start = 1 ;
1414
15- private boolean flag = false ;
15+ private boolean flag = false ;
1616
1717 public static void main (String [] args ) {
18- TwoThread twoThread = new TwoThread ();
18+ TwoThreadWaitNotify twoThread = new TwoThreadWaitNotify ();
1919
20- Thread t1 = new Thread (new TwoThread . OuNum (twoThread ));
20+ Thread t1 = new Thread (new OuNum (twoThread ));
2121 t1 .setName ("t1" );
2222
2323
24- Thread t2 = new Thread (new TwoThread . JiNum (twoThread ));
24+ Thread t2 = new Thread (new JiNum (twoThread ));
2525 t2 .setName ("t2" );
2626
2727 t1 .start ();
@@ -40,13 +40,18 @@ public OuNum(TwoThreadWaitNotify number) {
4040
4141 @ Override
4242 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 ++ ;
4843
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 {
5055 try {
5156 TwoThreadWaitNotify .class .wait ();
5257 } catch (InterruptedException e ) {
@@ -63,7 +68,7 @@ public void run() {
6368 /**
6469 * 奇数线程
6570 */
66- public static class JiNum implements Runnable {
71+ public static class JiNum implements Runnable {
6772 private TwoThreadWaitNotify number ;
6873
6974 public JiNum (TwoThreadWaitNotify number ) {
@@ -72,15 +77,22 @@ public JiNum(TwoThreadWaitNotify number) {
7277
7378 @ Override
7479 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 ++;
8086
81- number .flag = true ;
87+ number .flag = true ;
8288
8389 TwoThreadWaitNotify .class .notify ();
90+ }else {
91+ try {
92+ TwoThreadWaitNotify .class .wait ();
93+ } catch (InterruptedException e ) {
94+ e .printStackTrace ();
95+ }
8496 }
8597 }
8698 }
0 commit comments