首页 > 编程语言 > 详细

学习多线程5---Semaphore

时间:2015-02-08 19:26:45      阅读:190      评论:0      收藏:0      [点我收藏+]

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

}

  

学习多线程5---Semaphore

原文:http://www.cnblogs.com/hzmbbbb/p/4280288.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!