1.CountDownLatchDemo
package org.example;
import java.util.concurrent.CountDownLatch;
//计数器
/**
* 例子:
* 六个线程在教室 只有等这六个线程出门后 才能关门
*/
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
//总数是6
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i < 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"Go");
countDownLatch.countDown();//数量减1
},String.valueOf(i));
}
countDownLatch.await();//等待计数器归零 然后再向下执行
System.out.println("close door");
}
}
2.CyclicBarrier
package org.example;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/**
* 例子:集齐七颗龙珠召唤神龙
* 加法计数器
*/
public class CyclicBarrierDemo {
public static void main(String[] args) {
//召唤龙珠的线程
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
System.out.println("召唤神龙成功");
});
for (int i = 0; i < 7; i++) {
//lambda能操作到i吗
final int temp = i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"收集"+temp+"龙珠");
try {
cyclicBarrier.await();//等待 会进行计数
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
3.Semaphore信号量
package org.example;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* 例子:抢车位
* 六个车 三个车位
*/
public class SemaphoreDemo {
public static void main(String[] args) {
//线程数量 :停车位 限流
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i < 6; i++) {
new Thread(()->{
//acquire() 得到
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"抢到车位");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName()+"离开车位");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();//release() 释放
}
},String.valueOf(i+1)).start();
}
}
}
acquire() 获得,假设已经满了,等待,等待被释放为止
release() 释放 将当前信号量释放+1,唤醒等待的线程
作用:多个共享资源的互斥的使用 并发限流 控制最大线程数