java某个方法并发数控制
public class SemaphoreTest { private Semaphore mSemaphore=new Semaphore(5);
public void run(){
for(int i=0;i<100;i++){
new Thread(new Runnable(){
public void run(){
test();
}
}).start();
}
}
private void test(){
try {
mSemaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"开始执行");
try {
//业务方法
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"执行结束");
mSemaphore.release();
}
public static void main(String args) {
SemaphoreTest semaphoreTest=new SemaphoreTest();
semaphoreTest.run();
}
}