本人初学java,下面是一些比较简陋的代码,有不足之处,还请大家多多指教.
public class ABCPrinter {
public static int count = 0;
public static char flag = 'A';
public static Object obj = new Object();
public static void main(String[] args) {
new ABCPrinter().go();
}
private void go() {
Thread t1 = new Thread(new AThread1());
Thread t2 = new Thread(new BThread1());
Thread t3 = new Thread(new CThread1());
t1.start();t2.start();t3.start();
}
}
class AThread1 implements Runnable {
public void run() {
while(ABCPrinter.count<10) {
if(ABCPrinter.flag=='A') {
synchronized (ABCPrinter.obj) {
System.out.print("第" + ABCPrinter.count + "遍:A");
ABCPrinter.flag = 'B';
try {
ABCPrinter.obj.notifyAll();
ABCPrinter.obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class BThread1 implements Runnable {
public void run() {
while(ABCPrinter.count<10) {
if(ABCPrinter.flag == 'B') {
synchronized(ABCPrinter.obj) {
System.out.print("B");
ABCPrinter.flag = 'C';
try {
ABCPrinter.obj.notifyAll();
ABCPrinter.obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class CThread1 implements Runnable {
public void run() {
while(ABCPrinter.count<10) {
if(ABCPrinter.flag == 'C') {
synchronized(ABCPrinter.obj) {
System.out.println("C");
ABCPrinter.flag = 'A';
try {
ABCPrinter.obj.notifyAll();
ABCPrinter.count++;
ABCPrinter.obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}