CountDownLatch 、CyclicBarrier、Semaphore 使用
Semaphore 使用
public class SemaphoreDemo {
public static void main(String[] args) {
/**
* 多线程同时抢多个资源
* permits=1时,相当于锁
*
*/
Semaphore semaphore = new Semaphore(2);
for (int i = 0; i < 10; i++) {
new Thread(() -> {
try {
// 表示线程抢到了资源
semaphore.acquire();
System.out.println("线程" + Thread.currentThread().getName() + "抢到了车位");
TimeUnit.SECONDS.sleep(1);
System.out.println("线程" + Thread.currentThread().getName() + "离开了车位");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 资源释放
semaphore.release();
}
}, String.valueOf(i)).start();
}
}
}
CountDownLatch使用
public class CountDownLatchDemo {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 1; i <= 6; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "被灭!");
countDownLatch.countDown();
}, Country.getByCode(i)).start();
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("秦国统一六国~~~");
}
}
enum Country {
ZHAO(1, "赵国"),
WEI(2, "魏国"),
HAN(3, "韩国"),
QI(4, "齐国"),
CHU(5, "楚国"),
YAN(6, "燕国");
@Getter
private Integer code;
@Getter
private String name;
Country(Integer code, String name) {
this.code = code;
this.name = name;
}
public static String getByCode(Integer code) {
return Arrays.asList(Country.values()).stream()
.filter(o -> o.getCode() == code).findFirst()
.map(Country::getName).get();
}
}
CyclicBarrier 使用
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7);
for (int i = 1; i <= 7; i++) {
int finalI = i;
new Thread(() -> {
try {
System.out.println("集齐第" + finalI + "颗龙珠");
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}, String.valueOf(i)).start();
}
System.out.println("召唤神龙");
}