学习多线程5---Semaphore
Semaphore用于保证至多只有确定X条线程同时执行,系统在它们之间进行切换
下面是一个使用例子
package com.condition; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; public class SemaphoreTest { public static void main(String[] args) { ExecutorService threadPool = Executors.newCachedThreadPool(); final Semaphore semaphore = new Semaphore(4); for(int i = 0;i < 10;i++){ Runnable runnable = new Runnable(){ @Override public void run() { try { semaphore.acquire(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("*"+Thread.currentThread().getName() +" is into "+semaphore.availablePermits()); try { Thread.sleep((long) (Math.random()*10000)); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("*"+Thread.currentThread().getName() +" is leaving "); semaphore.release(); } }; threadPool.execute(runnable); } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。