Java编程面试题1

匿名网友 匿名网友 发布于: 2015-08-30 00:00:00
阅读 188 收藏 0 点赞 0 评论 0

设计两个线程类,一个线程类负责打印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();
}
}
}

评论列表
文章目录