并发编程必须掌握的三个辅助类
CountDownLatch
倒计时计数器
countDownLatch.countDown()
countDownLatch.await()
package com.example.juc;
import java.util.concurrent.CountDownLatch;
public class TestCountDownLatch {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i < 6; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "go out");
countDownLatch.countDown();
}, String.valueOf(i)).start();
}
countDownLatch.await();
System.out.println(countDownLatch.getCount() + "over");
}
}
结果:
0go out
5go out
4go out
2go out
3go out
1go out
0over
CyclicBarrier
简单理解为一个递增计数器
cyclicBarrier.await()
package com.example.juc;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class TestCyclicBarrier {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
System.out.println("集齐七颗龙珠,召唤出神龙!");
});
for (int i = 1; i <= 7; i++) {
final int temp = i;
new Thread(() -> {
System.out.println("收集到第" + temp + "颗");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
结果
收集到第1颗
收集到第7颗
收集到第5颗
收集到第6颗
收集到第4颗
收集到第3颗
收集到第2颗
集齐七颗龙珠,召唤出神龙!
Semaphore
semaphore.acquire()
semaphore.release()
package com.example.juc;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class TestSemaphore {
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(2);
System.out.println("第" + Thread.currentThread().getName() + "辆车开走了");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}, String.valueOf(i)).start();
}
}
}
第1辆车停好了
第3辆车停好了
第2辆车停好了
第2辆车开走了
第3辆车开走了
第1辆车开走了
第4辆车停好了
第6辆车停好了
第5辆车停好了
第4辆车开走了
第6辆车开走了
第5辆车开走了