减少计数CountDownLatch
CountDownLatch类可以设置一个计数器,然后通过countDown方法来进行减1的操作,使用await方法等待计数器不大于0,然后继续执行await方法之后的语句。”
- CountDownLatch主要有两个方法,当一个或多个线程调用await方法时,这
些线程会阻塞 - 其它线程调用countDown方法会将计数器减1(调用countDown方法的线程
不会阻塞) - 当计数器的值变为0时,因await方法阻塞的线程会被唤醒,继续执行
import java.util.concurrent.CountDownLatch;
public class demo2 {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i=1;i<=6;i++){
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"同学离开了教师");
countDownLatch.countDown();
},String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName()+"班长锁门了");
}
}
循环栅栏 CyclicBarrier
package com.yyp.callable;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class demo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
System.out.println("召唤神龙");
});
for (int i=1;i<=7;i++){
new Thread(()->{
try {
System.out.println(Thread.currentThread().getName()+"星龙被找到了");
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.valueOf(i)).start();
}
}
}
计数信号量
类似于锁,但是可以有n个线程可以拿到这个锁。
package com.yyp.callable;
import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class demo3 {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3);
for (int i=1 ;i<=6;i++){
new Thread(()->{
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"号抢到车位");
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
System.out.println(Thread.currentThread().getName()+"号----离开车位");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}