带有信号量及计数器的多线程线程池_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 带有信号量及计数器的多线程线程池

带有信号量及计数器的多线程线程池

 2013/8/14 4:09:48  chrischen214  程序员俱乐部  我要评论(0)
  • 摘要:packageorg.lance.concurrent;importjava.util.Random;importjava.util.concurrent.CountDownLatch;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.Semaphore;publicclassSemaphoreCountDownExecutor
  • 标签:多线程 信号量 线程
class="java" name="code">
package org.lance.concurrent;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreCountDownExecutor {

	private Semaphore semaphore;
	private CountDownLatch countDownLatch;
	private ExecutorService executor;
	
	
	public SemaphoreCountDownExecutor(final int semaphorePermits,final int count) {
		semaphore = new Semaphore(semaphorePermits);
		executor = Executors.newFixedThreadPool(semaphorePermits);
		countDownLatch = new CountDownLatch(count);
	}
	
	
	public void await(){
		try {
			countDownLatch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		executor.shutdown();
	}
	
	public void submit(final Runnable command) throws InterruptedException{
		countDownLatch.countDown();
		semaphore.acquire();
		try {
			executor.execute(new Runnable() {
				@Override
				public void run() {
					try {
						command.run();
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
						semaphore.release();
					}
				}
			});
		} catch (Exception e) {
			semaphore.release();
			e.printStackTrace();
		}
		
	}
	
	
	public static void main(String[] args) {
		int count = 100;
		SemaphoreCountDownExecutor executor = new SemaphoreCountDownExecutor(8, count);
		try {
			for (int i = 0; i < count; i++) {
				final int core = i;
				executor.submit(new Runnable() {
					@Override
					public void run() {
						System.out.println(core+"----------"+Thread.currentThread().getName());
						try {
							Thread.sleep(new Random().nextInt(1000));
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				});
			}
			executor.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
}

发表评论
用户名: 匿名