利用同步块和if条件交替输出
建议手动实现一遍
public class PrintNumber extends Thread {
private static int cnt = 0;
private int id;
public PrintNumber(int _id) {
id = _id;
}
public void run() {
while (cnt < 100) {
if (cnt % 2 == id) {
synchronized (PrintNumber.class) {
cnt++;
System.out.println("id:"+id+" cnt:"+cnt);
}
}
}
}
public static void main(String[] args) {
Thread t1 = new PrintNumber(0);
Thread t2 = new PrintNumber(1);
t1.start();
t2.start();
}
}