辅助类 CountDownLatch、CyclicBarrier、Semaphore
CountDownLatch的使用
/*
减法计数器
*/
public class Test1 {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(10);//一共减10次
for (int i = 1; i < 11; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName() + " Go Out");
countDownLatch.countDown();//每次减一
}, String.valueOf(i)).start();
}
countDownLatch.await();//等待计数器归零 再继续向下执行
System.out.println("Close Door");
}
}
CyclicBarrier的使用
/*
加法计数器
*/
public class Test {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, ()->{
System.out.println("集齐了龙珠");
});
for (int i = 1; i < 8; i++) {
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();
}
}*/
new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"收集第"+ temp +"颗龙珠");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
}, String.valueOf(temp)).start();
}
}
}
Semaphore的使用
/*
线程数量限制
*/
public class Test3 {
public static void main(String[] args) {
//线程数量 限流用
Semaphore semaphore = new Semaphore(3);
for (int i = 1; i < 7; 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();
}
}
}
浙公网安备 33010602011771号