方案一:
public class PrintABC {
public static void main(String[] args) {
AtomicInteger synObj = new AtomicInteger();
Runnable r = new ThreadModel(synObj);
new Thread(r,"A").start();
new Thread(r,"B").start();
new Thread(r,"C").start();
}
} public class ThreadModel implements Runnable {
public volatile AtomicInteger ato; public ThreadModel(AtomicInteger ato) {
this.ato = ato;
} public void run() {
for(int i=;i<;i++) {
synchronized(ato) {
if(ato.get()%==) {
System.out.println("A);
ato.set(ato.get()+);
ato.notifyAll();
} else if(ato.get()%==) {
System.out.println("B);
ato.set(ato.get()+);
ato.notifyAll();
} else if(ato.get()%==) {
System.out.println("C);
ato.set(ato.get()+);
ato.notifyAll();
} else {
ato.wait();
}
}
}
}
}
方案二:
public class printABC { public static void main(String [] args) {
AtomicInteger ato = new AtomicInteger();
ThreadModel modelA = new ThreadModel(ato,"A",);
ThreadModel modelB = new ThreadModel(ato,"B",);
ThreadModel modelC = new ThreadModel(ato,"C",);
new Thread(modelA).start();
new Thread(modelB).start();
new Thread(modelC).start();
} } public class ThreadModel { private AtomicInteger ato;
private String printChar;
private int flag;
private int count = ;
public ThreadModel(AtomicInteger ato,String printChar,int flag) {
this.ato = ato;
this.printChar = printChar;
this.flag = flag;
} public void run() {
synchronized(ato) {
while(true) {
if(ato.get()%==flag) {
System.out.println(printChar);
ato.set(ato.get()+);
ato.notifyAll();
count++;
if(count==) {
break;
}
}else {
ato.wait();
}
}
}
} }