Semaphore、CountDownLatch、CyclicBarrier

1、Semaphore的作用

信号量,用来限制能同时访问共享资源的线程上限

package com.sharing_model.juc;

import java.util.concurrent.Semaphore;

/**
 * 信号量,用来限制能同时访问共享资源的线程上限
 */
public class SemaphoreTest{
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("running");
                try {
                    Thread.sleep(1000);
                    System.out.println("end");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            }).start();
        }
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QXi952dZ-1607697546249)(C:/Users/lenovo/AppData/Roaming/Typora/typora-user-images/image-20201209203359384.png)]

2、改进数据库连接池

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fMFiICdM-1607697546255)(C:/Users/lenovo/AppData/Roaming/Typora/typora-user-images/image-20201209214851616.png)]

3、acquire

https://www.bilibili.com/video/BV16J411h7Rd?p=265

4、release

https://www.bilibili.com/video/BV16J411h7Rd?p=266

5、CountDownLatch

package com.sharing_model.juc;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch:用来进行线程同步协作,等待所有线程计数完成
 * 其中构造参数用来初始化等待计数值,await()用来等待计数归零,countDown()用来让计数减一
 */
public class CountdownLatchTest {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch cdl = new CountDownLatch(3);

        new Thread(() -> {
            System.out.println("线程1开始执行");
            try {
                Thread.sleep(1000);
                System.out.println("线程1完成");
                cdl.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            System.out.println("线程2开始执行");
            try {
                Thread.sleep(1500);
                System.out.println("线程2完成");
                cdl.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            System.out.println("线程3开始执行");
            try {
                Thread.sleep(2000);
                System.out.println("线程3完成");
                cdl.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        cdl.await();
        System.out.println("主线程等待完成");
    }
}

在线程池中使用countDownLatch

package com.sharing_model.juc;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 在线程池中使用CountDownLatch
 */
public class CountdownLatchTest2 {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch cdl = new CountDownLatch(3);
        ExecutorService pool = Executors.newFixedThreadPool(3);

        pool.submit(() -> {
            System.out.println("线程1开始执行");
            try {
                Thread.sleep(1000);
                System.out.println("线程1完成");
                cdl.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        pool.submit(() -> {
            System.out.println("线程2开始执行");
            try {
                Thread.sleep(1500);
                System.out.println("线程2完成");
                cdl.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        pool.submit(() -> {
            System.out.println("线程3开始执行");
            try {
                Thread.sleep(2000);
                System.out.println("线程3完成");
                cdl.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        cdl.await();
        System.out.println("主线程等待完成");
    }
}

模拟进度条

package com.sharing_model.juc;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 使用CountDownLatch模拟游戏界面的加载过程
 */
public class CountDownLatchTest3 {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch cdl = new CountDownLatch(10);
        ExecutorService pool = Executors.newFixedThreadPool(10);
        String[] schedule = new String[10];
        Random random = new Random();

        for (int i = 0; i < 10; i++) {
            int temp = i;
                pool.submit(() -> {
                    for (int j = 0; j <= 100; j++) {
                        schedule[temp] = j + "%";
                        try {
                            Thread.sleep(random.nextInt(500));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.print("\r" + Arrays.toString(schedule));
                    }
                    cdl.countDown();
                });
            }
        cdl.await();
        System.out.println( "\n" +"执行完成");
        }
    }

6、CyclicBarrier

循环栅栏,用来进行线程协作,等待线程满足某个计数。构造时设置【计数个数】,每个线程执行到某个需要同步的时刻调用await()方法进行等待,当等待的线程数满足【计数个数】是,继续执行。

package com.sharing_model.juc;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 循环栅栏,用来进行线程协作,等待线程满足某个计数。构造时设置【计数个数】,每个线程执行到某个需要同步的时刻调用await()方法进行等待,当等待的线程数满足【计数个数】是,继续执行。
 *
 * 和CountDownLatch最大的区别就是计数可以循环
 */
public class CyclicBarrierTest {
    public static void main(String[] args) {
        CyclicBarrier cb = new CyclicBarrier(2, () -> {
            System.out.println("t1 t2 end...");
        });
        ExecutorService pool = Executors.newFixedThreadPool(2);

        for (int i = 0; i < 3; i++) {
            pool.submit(() -> {
                System.out.println("t1 start..");
                try {
                    Thread.sleep(1000);
                    cb.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
            pool.submit(() -> {
                System.out.println("t2 start..");
                try {
                    Thread.sleep(1500);
                    cb.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值