网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

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

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 退出

成都创新互联公司2013年至今,先为宜川等服务建站,宜川等地企业,进行企业商务咨询服务。为宜川企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。

Process finished with exit code 0


分享标题:JAVA多线程限流解决并发问题
本文链接:http://bjjierui.cn/article/jjogpd.html

其他资讯