File tree Expand file tree Collapse file tree 2 files changed +91
-0
lines changed
src/main/java/com/crossoverjie/actual Expand file tree Collapse file tree 2 files changed +91
-0
lines changed Original file line number Diff line number Diff line change 66/**
77 * Function: 两个线程交替执行打印 1~100
88 *
9+ * lock 版
10+ *
911 * @author crossoverJie
1012 * Date: 11/02/2018 10:04
1113 * @since JDK 1.8
Original file line number Diff line number Diff line change 1+ package com .crossoverjie .actual ;
2+
3+ /**
4+ * Function:两个线程交替执行打印 1~100
5+ * 等待通知机制版
6+ *
7+ * @author crossoverJie
8+ * Date: 07/03/2018 13:19
9+ * @since JDK 1.8
10+ */
11+ public class TwoThreadWaitNotify {
12+
13+ private int start = 1 ;
14+
15+ private boolean flag = false ;
16+
17+ public static void main (String [] args ) {
18+ TwoThread twoThread = new TwoThread ();
19+
20+ Thread t1 = new Thread (new TwoThread .OuNum (twoThread ));
21+ t1 .setName ("t1" );
22+
23+
24+ Thread t2 = new Thread (new TwoThread .JiNum (twoThread ));
25+ t2 .setName ("t2" );
26+
27+ t1 .start ();
28+ t2 .start ();
29+ }
30+
31+ /**
32+ * 偶数线程
33+ */
34+ public static class OuNum implements Runnable {
35+ private TwoThreadWaitNotify number ;
36+
37+ public OuNum (TwoThreadWaitNotify number ) {
38+ this .number = number ;
39+ }
40+
41+ @ Override
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+
49+ number .flag = false ;
50+ try {
51+ TwoThreadWaitNotify .class .wait ();
52+ } catch (InterruptedException e ) {
53+ e .printStackTrace ();
54+ }
55+ }
56+ }
57+
58+ }
59+ }
60+ }
61+
62+
63+ /**
64+ * 奇数线程
65+ */
66+ public static class JiNum implements Runnable {
67+ private TwoThreadWaitNotify number ;
68+
69+ public JiNum (TwoThreadWaitNotify number ) {
70+ this .number = number ;
71+ }
72+
73+ @ Override
74+ 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+
81+ number .flag = true ;
82+
83+ TwoThreadWaitNotify .class .notify ();
84+ }
85+ }
86+ }
87+ }
88+ }
89+ }
You can’t perform that action at this time.
0 commit comments