黑马程序员技术交流社区
标题:
多线程打印ABC轮流3边,第二遍后卡死,找不出原因
[打印本页]
作者:
秦岩
时间:
2012-4-8 20:30
标题:
多线程打印ABC轮流3边,第二遍后卡死,找不出原因
package cn.copy;
/*
* 改造以下代码, 打印出如下形式:
* A 1
* A 2
* A 3
*
* B 1
* B 2
* B 3
*
* A 1
* A 2
* A 3
*
* B 1
* B 2
* B 3
*
* A 1
* A 2
* A 3
*
* B 1
* B 2
* B 3
*/
public class PrintTest {
public static void main(String[] args) {
final Printer printer = new Printer();
new Thread(){
public void run() {
for (int i = 0; i < 3; i++)
printer.print1();
};
}.start();
new Thread(){
public void run() {
for (int i = 0; i < 3; i++)
printer.print2();
};
}.start();
new Thread(){
public void run() {
for (int i = 0; i < 3; i++)
printer.print3();
};
}.start();
}
}
class Printer {
private int turn = 3; // 目前该轮到哪个方法了
public synchronized void print1() {
if (turn != 3){ // 如果不该1, 等待
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (turn == 3){
for (int i = 1; i <= 3; i++)
System.out.println("A " + i);
System.out.println();
turn = 1;// 1执行后该2
this.notifyAll();// 唤醒
}
}
public synchronized void print2() {
if (turn != 1){// 如果不该2, 等待
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (turn == 1) {
for (int i = 1; i <= 3; i++)
System.out.println("B " + i);
System.out.println();
turn = 2;// 2执行后该1
this.notifyAll();// 唤醒
}
}
public synchronized void print3() {
if (turn != 2){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (turn == 2) {
for (int i = 1; i <= 3; i++)
System.out.println("C " + i);
System.out.println();
turn = 3;
this.notifyAll();
}
}
}
复制代码
作者:
pray
时间:
2014-4-26 06:29
楼主出门来财,儿孙满堂!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2