CountDownLatch
是计数器, 线程完成一个就记一个, 就像 报数一样, 只不过是递减的。当减到0就会放行
相当于游戏的加载,只有所有玩家都加载完成,游戏才能进入
其中玩家相当于 分线程 , 整个游戏为main 线程
import java.util.Random;
import java.util.concurrent.CountDownLatch;
/**
*
*/
/***
* @author 18071
* @Date 2019年3月25日
* 功能: Java并发编程:CountDownLatch、CyclicBarrier和Semaphore
***/
public class test {
public static void main(String args[]) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(4);
for(int i = 0; i < latch.getCount(); i++){
new Thread(new mythread(latch), "player"+i).start();
}
System.out.println("正在等待所有玩家准备好");
latch.await();
System.out.println("开始游戏");
}
}
class mythread implements Runnable {
private CountDownLatch latch;
public mythread(CountDownLatch latch) {
this.latch=latch;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
// TODO Auto-generated method stub
Random rand = new Random();
int randomNum = rand.nextInt((3000 - 1000) + 1) + 1000;//产生1000到3000之间的随机整数
try {
Thread.sleep(randomNum);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" 已经准备好了, 所使用的时间为 "+((double)randomNum/1000)+"s");
//该线程完成 之后 使计数器减一,当所有线程 (或者是n个线程)完成之后 计数器 变为 0,继续执行主线程 main
latch.countDown();
}
}
CyclicBarrier
表示循环的障碍物,像一个水闸, 线程执行就想水流, 在水闸处都会堵住, 等到水满(线程到齐)了, 才开始泄流.
/**
*
*/
/***
* @author 18071
* @Date 2019年3月25日
* 功能:
***/
import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/**
*
*/
/***
* @author 18071
* @Date 2019年3月25日
* 功能:
***/
public class enn {
public static void main(String args[]) {
CyclicBarrier barrier =new CyclicBarrier (3) ;
for(int i=0;i<3;i++) {
new Thread( new mythrea1(barrier),"队友"+i).start();
}
System.out.println("main function is finished.");
}
}
class mythrea1 implements Runnable {
CyclicBarrier barrier ;
public mythrea1(CyclicBarrier barrier) {
this.barrier=barrier;
}
@Override
public void run() {
for(int i=1;i<6;i++)
{
Random rand = new Random();
int randomNum = rand.nextInt((3000 - 1000) + 1) + 1000;//产生1000到3000之间的随机整数
try {
Thread.sleep(randomNum);
try {
barrier.await();
} catch (BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" 已经越过了第"+i+"个拦截物, 所使用的时间为 "+((double)randomNum/1000)+"s");
}
}
}
每次都必须3个线程都执行了 barrier.await(); 使其 等于3之后 才会开始下一轮 进行