打印10个偶数然后再打印10个奇数

2014-07-06 06:30:02 阅读( 199 )

1949人 收藏本页

标签:Java面试题

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();
}
}
}

来自IT公司面试手册

下一篇:java开发人员面试总结。

上一篇:java读取properties文件

亲~ 如果您有更好的答案 可在评论区发表您独到的见解。

您想查看更多的信息: 面试题