码迷,mamicode.com
首页 > 编程语言 > 详细

学习多线程5---Semaphore

时间:2015-02-08 19:27:25      阅读:151      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!