设为首页 加入收藏

TOP

打印10个偶数然后再打印10个奇数
2014-11-24 01:35:01 来源: 作者: 【 】 浏览:11
Tags:打印 偶数 然后 奇数

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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Java编程面试题1 下一篇广州-迈达威维佳.net

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: