实用多线程类
这些类都是位于java.concurrent.util.*包下。
CountDownLatch
常用于监听某些初始化操作,等待初始化这些完毕,通知主线程继续工作。针对的是一个线程,一个线程等待,其他线程通知。
public class U01CountDownLatch { public static void main(String[] args) {
//代表countDown方法调用的次数,只有调用次数达到了阻塞的线程才会开始执行 CountDownLatch countDownLatch = new CountDownLatch(2);
//案例:某应用,启动之前要加载A配置文件、B配置文件 new Thread(new Runnable() { @Override public void run() { System.out.println("=== t1 开始启动"); try { //开始await countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("=== t1 启动完成"); } },"t1").start();
new Thread(new Runnable() { @Override public void run() { System.out.println("开始加载配置文件t2"); //第一次countDown countDownLatch.countDown(); System.out.println("加载配置文件t2完成"); } },"t2").start();
new Thread(new Runnable() { @Override public void run() { System.out.println("开始加载配置文件t3"); //第二次countDown countDownLatch.countDown(); System.out.println("加载配置文件t3完成"); } },"t3").start();
} } |
CyclicBarrier
假设每个线程代表一个跑步运动员,当运动员都准备好后,才一起出发,只要有一个人没有准备好,所有人都要等待。针对的是多个线程,多个线程完成才完成。
public class U02CyclicBarrier { public static void main(String[] args) { //指定运动员数量 CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(2); newFixedThreadPool.submit(new Athlete("A",cyclicBarrier)); newFixedThreadPool.submit(new Athlete("B",cyclicBarrier)); // newFixedThreadPool.submit(new Athlete("C",cyclicBarrier)); newFixedThreadPool.shutdown(); } } class Athlete implements Runnable {
private String name;
private CyclicBarrier cyclicBarrier;
public Athlete(String name, CyclicBarrier cyclicBarrier) { super(); this.name = name; this.cyclicBarrier = cyclicBarrier; }
@Override public void run() { int readyTime = new Random().nextInt(5) * 1000; System.out.println("运动员准备时间:" + readyTime);
try { Thread.sleep(readyTime); cyclicBarrier.await(); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); }
System.out.println("开跑。。。"); } } |
Semaphore
信号量,是用于线程线程同时运行的数量,非常适合高并发访问,拿到信号量的线程可以进入,否则就等待,通过acquire()和release()获取和释放访问许可。
public class U03Semaphore { public static void main(String[] args) {
//线程池 ExecutorService pool = Executors.newCachedThreadPool();
//每次只允许3个线程同时处理任务 Semaphore semaphore = new Semaphore(3);
//模拟 for (int i = 0; i < 100; i++) { int num = i; pool.execute(new Runnable() { @Override public void run() {
try { //获得许可 semaphore.acquire();
System.out.println(num + " 处理......"); Thread.sleep(new Random().nextInt(3) * 1000);
//处理完业务逻辑释放 semaphore.release(); } catch (InterruptedException e) { e.printStackTrace(); } } }); }
pool.shutdown(); } } |