JUC常用辅助类
CountDownLatch
可以记录一个数,调用countDown()数字减1,当数字为0的时候,会通知所有调用await()的线程放行。
package vc.coding.juc;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(5); for (int i = 1; i <= 5; i++) { new Thread(() -> { System.out.println("线程" + Thread.currentThread().getName() + "启动"); countDownLatch.countDown(); }, String.valueOf(i)).start(); } countDownLatch.await(); System.out.println(Thread.currentThread().getName() + "线程完毕"); } }
|
CyclicBarrier
作用与CountDownLatch相反,同样可以记录一个数,当调用await()的线程数等于这个数时,才执行执行指定的操作。
package vc.coding.juc;
import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierDemo { public static void main(String[] args) { CyclicBarrier cyclicBarrier = new CyclicBarrier(5, () -> { System.out.println("召唤神龙!"); }); for (int i = 1; i <= 7; i++) { final int tempI = i; new Thread(() -> { try { System.out.println(Thread.currentThread().getName() + "收集了第" + tempI + "颗龙珠"); cyclicBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } }, String.valueOf(i)).start(); } } }
|
Semaphore
指定一个信号量。
每次调用acquire()的时候信号量-1,当信号量为0时,就会一直等待,直到信号量不为0。
每次调用release()的时候信号量+1。
package vc.coding.juc;
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit;
public class SemaphoreDemo { static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("mm分ss秒");
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() + "线程抢到了执行权限" + dateTimeFormatter.format(LocalDateTime.now())); TimeUnit.SECONDS.sleep(3); System.out.println(Thread.currentThread().getName() + "线程释放了执行权限"); } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } }, String.valueOf(i)).start(); } } }
|
测试单例模式不加valitale为什么会不完全
怎么解决死锁