JUC编程(四)-常用工具类
六.常用工具类
CountDownLatch:
-
允许一个或多个线程等待直到在其他线程执行的一组操作完成才开始执行。(计数)
- 创建CountDownLatch示例时给定计数值。通过await()阻塞,直到由于countDown()方法的调用(计数减一)而导致当前计数达到零,之后所有等待线程开始执行。
-
public class CountDown { public static void main(String[] args) throws InterruptedException { CountDownLatch count = new CountDownLatch(5); for (int i = 0; i < 5; i++) { new Thread(()->{ System.out.println(Thread.currentThread().getName()+"in"); count.countDown(); }).start(); } count.await(); System.out.println("out"); } } -
Thread-1in Thread-0in Thread-3in Thread-4in Thread-2in out
CyclicBarrier:
- 允许一组线程全部等待彼此达到共同屏障点。 循环阻塞在涉及固定大小的线程方的程序中很有用,这些线程必须偶尔等待彼此。 屏障被称为循环 ,因为它可以在等待的线程被释放之后重新使用。
- CyclicBarrier(int parties, Runnable barrierAction) ,当给定数量(parties)的线程执行完之后,执行barrierAction。
-
public class CountUp { public static void main(String[] args) { CyclicBarrier cyclicBarrier = new CyclicBarrier(5,()->{ System.out.println("5"); }); for (int i = 1; i <= 5; i++) { new Thread(()->{ System.out.println(Thread.currentThread().getName()); try { cyclicBarrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } }).start(); } } } -
Thread-0 Thread-2 Thread-3 Thread-1 Thread-4 5
Semaphore:
- 计数信号量。Semaphore设置可用数量的计数。用于限制线程数。在概念上,信号量维持一组许可证。 如果有必要,每个acquire()都会阻塞,直到许可证可用,然后才能使用它。 每个release()添加许可证,潜在地释放阻塞获取方。 但是,没有使用实际的许可证对象; Semaphore只保留可用数量的计数,并相应地执行。
-
public class Semap { public static void main(String[] args) { Semaphore semaphore = new Semaphore(3); for (int i = 1; i <= 10; i++) { new Thread(() -> { try { semaphore.acquire(); System.out.println(Thread.currentThread().getName() + " get the resource"); TimeUnit.SECONDS.sleep(2); System.out.println(Thread.currentThread().getName() + " release the resource"); } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } }).start(); } } } -
Thread-1 get the resource Thread-0 get the resource Thread-0 release the resource Thread-1 release the resource Thread-3 get the resource Thread-2 get the resource Thread-2 release the resource Thread-3 release the resource Thread-4 get the resource Thread-4 release the resource

浙公网安备 33010602011771号