少年他曾来过

导航

 

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

}

  

posted on 2015-02-08 18:25  少年他曾来过  阅读(133)  评论(0编辑  收藏  举报