刚才写的利用Java多线程顺序打印10次ABC的小程序
/**
* 顺序10次打印ABC
* @author Administrator
*
*/
public class ThreadPrint {
public static void main(String[] args) {
A a = new A();
for(int i=0;i<10;i++) {
MyThread mt1 = new MyThread(a);
mt1.start();
}
}
}
class A {
private char[] c = {'A','B','C'};
private int index;
public char[] getC() {
return c;
}
public synchronized void execute() {
if(index >= c.length) {
index = 0;
} else {
System.out.println(c[index++]);
}
}
}
class MyThread extends Thread{
private A a;
public MyThread4(A a) {
this.a = a;
}
public void run() {
synchronized (a) {
int index = a.getC().length;
for(int i=0;i<=index;i++) {
a.execute();
}
System.out.println("===============");
}
}
}