ITeye博客

java某个方法并发数控制

jackaney · 2019-01-06 14:01 · 多线程 · 编程语言 · Markdown

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();
}

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。