1 package cn.thread;
2
3 public class ManyThread2 {
4 public static void main(String[] args) {
5 MyRunnable1 runnable1 = new MyRunnable1();
6 MyRunnable2 runnable2 = new MyRunnable2();
7 MyRunnable3 runnable3 = new MyRunnable3();
8
9 Thread t1 = new Thread(runnable1, "线程1");
10 Thread t2 = new Thread(runnable2, "线程2");
11 Thread t3 = new Thread(runnable3, "线程3");
12
13 t1.start();
14 t2.start();
15 t3.start();
16 }
17 }
18
19 class Print {
20 public static int count = 0;
21 public static Object obj = new Object();
22 public static int x = 1;
23
24 public static void print1(int i) {
25 synchronized (obj) {
26 if (x == 1) {
27 for (int j = 0; j < 5; j++) {
28 count++;
29 System.out.println(Thread.currentThread().getName() + ":"+ count+"____i="+i);
30 }
31 x = 2;
32 try {
33 Thread.sleep(200);
34 } catch (InterruptedException e) {
35 e.printStackTrace();
36 }
37 obj.notifyAll();
38 } else {
39 try {
40 obj.wait();
41 } catch (InterruptedException e) {
42 e.printStackTrace();
43 }
44 }
45 }
46 }
47
48 public static void print2(int i) {
49 synchronized (obj) {
50 if (x == 2) {
51 for (int j = 0; j < 5; j++) {
52 count++;
53 System.out.println(Thread.currentThread().getName() + ":"+ count+"____i="+i);
54 }
55 x = 3;
56 try {
57 Thread.sleep(200);
58 } catch (InterruptedException e) {
59 e.printStackTrace();
60 }
61 obj.notifyAll();
62 } else {
63 try {
64 obj.wait();
65 } catch (InterruptedException e) {
66 e.printStackTrace();
67 }
68 }
69 }
70 }
71
72 public static void print3(int i) {
73 synchronized (obj) {
74 if (x == 3) {
75 for (int j = 0; j < 5; j++) {
76 count++;
77 System.out.println(Thread.currentThread().getName() + ":"+ count+"____i="+i);
78 }
79 x = 1;
80 try {
81 Thread.sleep(200);
82 } catch (InterruptedException e) {
83 e.printStackTrace();
84 }
85 obj.notifyAll();
86 } else {
87 try {
88 obj.wait();
89 } catch (InterruptedException e) {
90 e.printStackTrace();
91 }
92 }
93 }
94 }
95 }
96
97 class MyRunnable1 implements Runnable {
98 @Override
99 public void run() {
100 for (int i = 0; i < 10; i++) {
101 if (Print.count <= 55) {
102 Print.print1(i);
103 }
104 }
105 }
106 }
107
108 class MyRunnable2 implements Runnable {
109 @Override
110 public void run() {
111 for (int i = 0; i < 10; i++) {
112 if (Print.count <= 55) {
113 Print.print2(i);
114 }
115 }
116 }
117 }
118
119 class MyRunnable3 implements Runnable {
120 @Override
121 public void run() {
122 for (int i = 0; i < 10; i++) {
123 if (Print.count < 50) {
124 Print.print3(i);
125 }
126 }
127 }
128 }