JAVA多线程限流解决并发问题

发布时间:2020-06-30 08:21:21 作者:恋上程序员
来源:网络 阅读:516
package concurrent;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Auth: zhouhongliang
 * Date:2019/8/1
 * 并发限流功能
 * Semaphore
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 10; i++) {
            executorService.execute(() -> {
                try {
                    //semaphore.acquire();//一直等待
                    if (semaphore.tryAcquire(3, TimeUnit.SECONDS)) {//等待3秒
                        play();
                        semaphore.release();
                    } else {
                        System.out.println(Thread.currentThread().getName() + " 进入超时");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {

                }
            });
        }
        executorService.shutdown();
    }

    /**
     * 模拟任务
     */
    public static void play() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(simpleDateFormat.format(new Date()) + " " + Thread.currentThread().getName() + " 进入");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(simpleDateFormat.format(new Date()) + " " + Thread.currentThread().getName() + " 退出");
    }
}

输出结果:
2019-08-01 11:09:50 pool-1-thread-1 进入
2019-08-01 11:09:50 pool-1-thread-3 进入
2019-08-01 11:09:50 pool-1-thread-2 进入
2019-08-01 11:09:52 pool-1-thread-3 退出
2019-08-01 11:09:52 pool-1-thread-1 退出
2019-08-01 11:09:52 pool-1-thread-2 退出
2019-08-01 11:09:52 pool-1-thread-4 进入
2019-08-01 11:09:52 pool-1-thread-5 进入
2019-08-01 11:09:52 pool-1-thread-6 进入
pool-1-thread-7 进入超时
pool-1-thread-8 进入超时
pool-1-thread-9 进入超时
pool-1-thread-10 进入超时
2019-08-01 11:09:54 pool-1-thread-6 退出
2019-08-01 11:09:54 pool-1-thread-5 退出
2019-08-01 11:09:54 pool-1-thread-4 退出

Process finished with exit code 0

推荐阅读:
  1. Linux高并发系统之限流技术
  2. Java怎么解决高并发的问题

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

semaphore executors ava

上一篇:mongoDB基本操作(二)-(CRUD)

下一篇:Kubernetes解决了Docker使用中的哪些问题?

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》