java 多线程应用循环输出abc
有三个线程id分别是a、b、c,请用多线编程实现,在屏幕上循环打印10次abcabc
请补充以下代码
public class test {
public static void main(string[] args) {
majusculeabc maj = new majusculeabc();
thread t_a = new thread(new thread_abc(maj , 'a'));
thread t_b = new thread(new thread_abc(maj , 'b'));
thread t_c = new thread(new thread_abc(maj , 'c'));
t_a.start();
t_b.start();
t_c.start();
}
}
class majusculeabc {
请补充代码
}
class thread_abc implements runnable {
请补充代码
}答案如下
public class threadtest {
public static void main(string[] args) throws interruptedexception {
majusculeabc maj = new majusculeabc();
thread t_a = new thread(new thread_abc(maj , 'a'));
thread t_b = new thread(new thread_abc(maj , 'b'));
thread t_c = new thread(new thread_abc(maj , 'c'));
t_a.start();
t_b.start();
t_c.start();
}
private static class majusculeabc {
// 请补充代码
public majusculeabc() {
}
private int a = 1;
private synchronized void print(int index, char s) throws interruptedexception {
do {
if (s == 'a' && a == 1) {
a++;
system.out.println(index+"---" + s);
notifyall();
break;
} else if (s == 'b' && a == 2) {
a++;
system.out.println(index+"---" + s);
notifyall();
break;
} else if (s == 'c' && a == 3) {
a = 1;
system.out.println(index+"---" + s);
notifyall();
break;
} else {
wait();
}
} while (true);
}
}
private static class thread_abc implements runnable {
private char s;
private majusculeabc majusculeabc;
// 请补充代码
public thread_abc(majusculeabc majusculeabc, char s) {
this.majusculeabc = majusculeabc;
this.s = s;
}
@override
public void run() {
for (int i = 0; i < 10; i++) {
try {
majusculeabc.print(i, s);
} catch (interruptedexception e) {
e.printstacktrace();
}
}
}
}
}输出如下:
0---a
0---b
0---c
1---a
1---b
1---c
2---a
2---b
2---c
3---a
3---b
3---c
4---a
4---b
4---c
5---a
5---b
5---c
6---a
6---b
6---c
7---a
7---b
7---c
8---a
8---b
8---c
9---a
9---b
9---c
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论