设为首页 加入收藏

TOP

Java编程面试题1
2014-11-24 01:35:01 来源: 作者: 【 】 浏览:3
Tags:Java 编程 试题

设计两个线程类,一个线程类负责打印100以内所有的偶数,另一个线程打印100以内所有的奇数。要求偶数线程每打印10个偶数以后,就让奇数线程打印10个奇数,如此交替进行。


public class printThread extends Thread {


public static void main(String[] args) throws Exception {
CyclicBarrier barrier = new CyclicBarrier(2);
new printThread(barrier,true, 0).start();
new printThread(barrier,false, 1).start();
}


int numberic;
boolean isEven;
private CyclicBarrier barrier;
public printThread(CyclicBarrier barrier,boolean isEven, int numberic) {
this.barrier = barrier;
this.isEven = isEven; //true,双数打印;false,单数打印
this.numberic = numberic;//从什么值,开始连续打印50个双(单)数
}
public synchronized int printNumberic(int numberic) {
int count = 0;
if (isEven) {
System.out.print(“十个偶数是:”);
} else {
System.out.print(“十个奇数是:”);
}
while (count < 10) {
System.out.print(numberic + “,”);
numberic = numberic + 2;
count = count + 1;
}
return numberic;
}
public void run() {
try {
while (numberic < 100) {
if (!isEven){
sleep(2000);//先打印双数,利用sleep()做出时间间隔,后打印单数
}else{
sleep(1000);//为演示效果,控制打印双数的时间间隔
}
numberic = this.printNumberic(numberic);
System.out.println();
barrier.await();//使用barrier保证每打印一组双数和一组单数后,继续递增式打印
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇广州-品高软件(.net) 下一篇打印10个偶数然后再打印10个奇数

评论

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