3个线程分别交替输出xyz字符,输出10遍
一位群友分享的**公司面试题
3个线程分别交替输出xyz字符,输出10遍
public class XYZ implements Runnable {
private static AtomicInteger atomicInteger = new AtomicInteger();
private int index;
public XYZ(int index) {
this.index = index;
}
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
new Thread(new XYZ(i)).start();
}
}
@Override
public void run() {
int i = 0;
while (i < 10) {
synchronized (XYZ.class) {
if (atomicInteger.get() % 3 == this.index) {
System.out.print(Character.toString((char) ('x' + index)));
i++;
atomicInteger.incrementAndGet();
//输出最后一个字符的时候换行
if (index == 2){
System.out.println();
}
}
}
}
}
}
输出效果