java多线程问题_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 退出

Process finished with exit code 0

原文:https://blog.51cto.com/11147669/2425542

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值