修改别人的错误多线程
话不多说,先上错误代码:
1
2 /**
3 * 编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,
4 * 要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推
5 * @author Fantastic_Rebo
6 *
7 */
8
9 public class Play2 {
10 static public int num=1;
11 public static void main(String[] args) throws InterruptedException {
12 Object o=new Object();
13 A2 a2=new A2(o);
14 B2 b2=new B2(o);
15 C2 c2=new C2(o);
16
17 Thread t1=new Thread(a2,"A---");
18 Thread t2=new Thread(b2,"B---");
19 Thread t3=new Thread(c2,"C---");
20
21 t1.start();
22 t2.start();
23 t3.start();
24
25 for (int i = 1; i >0; i++) {
26 if(i%3==1) {
27 t1.start();
28 }else if(i%3==2) {
29 t2.start();
30 }else if(i%3==0) {
31 t3.start();
32 }
33 }
34
35
36 }
37 }
38 class A2 implements Runnable{
39 Object o;
40 public A2(Object o) {
41 super();
42 this.o = o;
43 }
44 @Override
45 public void run() {
46
47 if(num%3==1) {
48 num++;
49 for (int i = 1; i <=10; i++) {
50 synchronized (o) {
51 o.notify();
52 System.out.println(Thread.currentThread().getName()+i);
53 try {
54 o.wait();
55 } catch (InterruptedException e) {
56 e.printStackTrace();
57 }
58 }
59 }
60 }else {
61 try {
62 o.wait();
63 } catch (InterruptedException e) {
64 // TODO Auto-generated catch block
65 e.printStackTrace();
66 }
67 }
68
69 }
70
71 }
72 class B2 implements Runnable{
73 Object o;
74 int num;
75 public B2(Object o) {
76 super();
77 this.o = o;
78 }
79 @Override
80 public void run() {
81 if(num%3==2) {
82 num++;
83 for (int i = 1; i <=10; i++) {
84 synchronized (o) {
85 o.notify();
86 System.out.println(Thread.currentThread().getName()+i);
87 try {
88 o.wait();
89 } catch (InterruptedException e) {
90 e.printStackTrace();
91 }
92 }
93 }
94 }else {
95 try {
96 o.wait();
97 } catch (InterruptedException e) {
