public class Counter {
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new CounterThread(counter, 0);
Thread t2 = new CounterThread(counter, 1);
t1.start();
t2.start();
}
public synchronized void countEven() {
try {
for (int i = 2; i <= 100; i += 2) {
System.out.printf(“%d,”, i);
if (i % 20 == 0) {
System.out.println();
notifyAll();
if (i < 100) {
wait();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public synchronized void countOdd() {
try {
for (int i = 1; i < 100; i += 2) {
System.out.printf(“%d,”, i);
if ((i + 1) % 20 == 0) {
System.out.println();
notifyAll();
if (i < 99) {
wait();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class CounterThread extends Thread {
Counter counter;
int flag;
public CounterThread(Counter counter, int flag) {
this.counter = counter;
this.flag = flag;
}
public void run() {
if (flag % 2 == 0) {
counter.countEven();
} else {
counter.countOdd();
}
}
}
评论列表
文章目录