Java 4个线程交替打印0到400
package learn_thread;
public class Demo6 {
private static final int ThreadNum = 4;
public static void main(String[] args) {
CyclePrint cyclePrint = new CyclePrint();
for (int i = 0; i < ThreadNum; i++) {
final int curFlag = i;
final int nextFlag = (curFlag + 1) % ThreadNum;
new Thread(new Runnable() {
@Override
public void run() {
cyclePrint.print(curFlag, nextFlag, curFlag, ThreadNum);
}
}, "T" + curFlag).start();
}
}
}
class CyclePrint {
private static int flag = 0;
private static final int maxValue = 400;
public void print(int curFlag, int nextFlag, int start, int threadNum) {
for (int i = start; i <= maxValue; i += threadNum) {
synchronized (this) {
while (curFlag != flag) {
try {
wait();
} catch (InterruptedException e) {
}
}
System.out.println(Thread.currentThread().getName() + "-" + i);
flag = nextFlag;
notifyAll();
}
}
}
}