zoukankan      html  css  js  c++  java
  • 学习多线程5---Semaphore

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

      

  • 相关阅读:
    mySQL教程 第1章 数据库设计
    数学符号大全
    C# 正则表达式 判断各种字符串(如手机号)
    C# 面向对象编程
    博客园 网址
    优化正则表达式的诀窍
    hdu 1596 floyd
    poj3259,简单判断有无负环,spfa
    hdu 1496 hash
    hdu 1429 bfs+二进制状态压缩
  • 原文地址:https://www.cnblogs.com/hzmbbbb/p/4280288.html
Copyright © 2011-2022 走看看