Semaphore计数器,计数获取到才执行,没获取到,就阻塞等待
对比:CountDownLatch计数器,它不阻塞各个计数的地方,但是阻塞总计数的地方;
CyclicBarrier栅栏,它阻塞它存在的地方,唯有大家都到齐了,才开始跑;
public class test {
java.util.concurrent.Semaphore semaphore = new java.util.concurrent.Semaphore(2);
public class A implements java.lang.Runnable{
java.util.concurrent.Semaphore semaphore;
int threadName;
public A(java.util.concurrent.Semaphore semaphore,int threadName){
this.semaphore = semaphore;
this.threadName = threadName;
}
public void run(){
try {
System.out.println(this.threadName+"开始");
this.semaphore.acquire();
System.out.println(this.threadName+"获取到茅坑");
Thread.sleep(10000);
System.out.println(this.threadName+"结束");
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
this.semaphore.release();
}
}
}
public static void main(String[] args) throws ParseException {
test a = new test();
for(int i=1;i <=5;i++){
new Thread(new test().new A(a.semaphore,i)).start();
}
}
}