您的位置:首页 > 其它

多线程循环打印ABC10次

2012-03-21 20:44 363 查看
package rainbow.thread;

public class PrintABC {

private int counta = 0, countb = 0, countc = 0;

private boolean printa = false, printb = false, printc = false;

private int printcount = 0;

public void printa(){
synchronized(this){
while(!(printcount == 0 || (printb && printc))){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("A");
printa = true;
//reset
printb = printc = false;
counta++;
printcount++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
notifyAll();
}
}

public void printb(){
synchronized(this){
while(!printa || (counta - countb == 0)){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("B");
printb = true;
countb++;
printcount++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
notifyAll();
}
}

public void printc(){
synchronized(this){
while(!printb || (countb - countc == 0)){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("C");
printc = true;
//reset a
printa = false;
countc++;
printcount++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
notifyAll();
}

}

public int getPrintcount() {
return printcount;
}

public void setPrintcount(int printcount) {
this.printcount = printcount;
}

}


package rainbow.thread;

public class PrintThread implements Runnable {

private PrintABC abc = null;

public PrintThread(PrintABC abc){
this.abc = abc;
}

public void run() {
while(abc.getPrintcount() <= 30){
abc.printa();
}
}

}


package rainbow.thread;

public class TestThread {

public static void main(String[] args) {
PrintABC abc = new PrintABC();

new Thread(new PrintThread(abc)).start();
new Thread(new PrintThread1(abc)).start();
new Thread(new PrintThread2(abc)).start();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: