三个线程交替打印ABC,例如ABCABCABC,代码如下:
/**
* GEEK
* Description:爱学Java
* @author :LiGer
*/
public class Test {
public static void main(String[] args) {
printABC print = new printABC(100);
new Thread(new Runnable() {
@Override
public void run() {
try {
print.printA();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
print.printB();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
try {
print.printC();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
class printABC {
int num;
int flag=1;
printABC(int i) {
this.num=i;
}
public synchronized void printA() throws InterruptedException {
int i=num;
while (i>0){
if(flag==1){
System.out.println('A');
i--;
flag=2;
this.notifyAll();
}else{
this.wait();
}
}
}
public synchronized void printB() throws InterruptedException {
int i=num;
while (i>0){
if(flag==2){
System.out.println('B');
i--;
flag=3;
this.notifyAll();
}else{
this.wait();
}
}
}
public synchronized void printC() throws InterruptedException {
int i=num;
while (i>0){
if(flag==3){
System.out.println('C');
i--;
flag=1;
this.notifyAll();
}else{
this.wait();
}
}
}
}