J.U.C工具包之Semaphore
什么是Semaphore:
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; public class SemaphoreDemo { public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool(); // 最多5个线程同时访问 Semaphore semaphore = new Semaphore(5); for (int i = 0; i < 10; i++) { int num = i; Runnable task = new Runnable() { @Override public void run() { try { semaphore.acquire(); System.out.println("Thread:" + Thread.currentThread().getName() + "num is:" + num + " starttime:" + System.currentTimeMillis()); Thread.sleep(5000); semaphore.release(); } catch (InterruptedException e) { e.printStackTrace(); } } }; executorService.execute(task); } executorService.shutdown(); } } |
执行结果:
1 2 3 4 5 6 7 8 9 10 11 |
Thread:pool-1-thread-2num is:1 starttime:1596530701355 Thread:pool-1-thread-1num is:0 starttime:1596530701355 Thread:pool-1-thread-3num is:2 starttime:1596530701355 Thread:pool-1-thread-5num is:4 starttime:1596530701355 Thread:pool-1-thread-4num is:3 starttime:1596530701355 /**这里开始因为已经有5个线程同时访问了,所以要等待那5个执行完成释放后,后续的才能继续获取资源执行*/ Thread:pool-1-thread-6num is:5 starttime:1596530706357 Thread:pool-1-thread-10num is:9 starttime:1596530706357 Thread:pool-1-thread-9num is:8 starttime:1596530706357 Thread:pool-1-thread-7num is:6 starttime:1596530706357 Thread:pool-1-thread-8num is:7 starttime:1596530706357 |
暂无评论