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();
}
}
}
作者: 陈科宇 时间: 2013-2-3 21:01
public class ThreadTest {
private boolean flag=false;//判断一个线程是否执行完成
private int odd_num=-1;//奇数
private int even_num=0;//偶数
/**
* 输出奇数
*/