zoukankan      html  css  js  c++  java
  • Semaphore初探

     示例一:

    package com.smbea.demo.semaphore;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Semaphore;
    
    /**
     * Semaphore 用于为线程加锁与释放锁
     * @author hapday
     * @2017年1月16日 @下午8:50:55
     */
    public class SemaphoreTest {
    
    	public static void main(String[] args) {
    		int permissionCount = 5;	// 许可数
    		ExecutorService executorService = Executors.newCachedThreadPool();
    		final Semaphore semaphore = new Semaphore(permissionCount);		// 声明并实例化“许可数”为 5 的 Semaphore 实例
    		
    		for(int index = 0; index < 10; index++) {
    			try {
    				// 休眠 0.1 秒
    				Thread.sleep(100);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    			
    			Runnable runnable = new Runnable() {
    
    				@Override
    				public void run() {
    					try {
    						// 当前线程请求获取 semaphore 的“许可”;如果获得了 semaphore 的“许可”则此线程继续则行,并且 semaphore 的许可数减一;否则此线程进入阻塞状态。
    						semaphore.acquire();
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    					
    					System.out.println("线程:" + Thread.currentThread().getName() + " 进入,当前已有 " + (permissionCount - semaphore.availablePermits()) + " 个并发线程。");
    					
    					try {
    						Thread.sleep((long) (Math.random() * 10000));
    //						Thread.sleep(10000);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    					
    					System.out.println("线程:" + Thread.currentThread().getName() + " 即将离开...");
    					semaphore.release();	// 将当前的线程释放“许可数”,semaphore 的许可数加一,至于哪个线程先离开没有固定的顺序
    					System.out.println("线程:" + Thread.currentThread().getName() + " 已离开,当前已有 " + (permissionCount - semaphore.availablePermits()) + " 个并发线程已离开。");
    				}
    				
    			};
    			
    			executorService.execute(runnable);
    		}
    	}
    
    }
    

      

    示例二:

    package com.smbea.demo.semaphore;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Semaphore;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    /**
     * Semaphore 用于为线程加锁与释放锁
     * @author hapday
     * @2017年1月16日 @下午8:50:55
     */
    public class SemaphoreTest2 {
    
    	public static void main(String[] args) {
    		int permissionCount = 5;	// 许可数
    		ExecutorService executorService = Executors.newFixedThreadPool(permissionCount);
    		Counter counter = new Counter();
    		
    		for(int index = 0; index < 8; index++) {
    			try {
    				// 休眠 0.1 秒
    				Thread.sleep(100);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    			
    			executorService.execute(new Runnable() {
    
    				@Override
    				public void run() {
    					counter.calculate();
    				}
    				
    			});
    			
    		}
    		
    		executorService.shutdown();
    		
    	}
    
    	public static class Counter {
    		private int count = 0;
    		Lock lock = new ReentrantLock();
    		int permissionCount = 5;	// 许可数
    		Semaphore semaphore = new Semaphore(permissionCount);
    		
    		public void calculate() {
    //			lock.lock();
    			try {
    				// 当前的线程请求获取“锁”
    				semaphore.acquire();
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    			
    			try {
    				count++;
    					
    				try {
    					// 休眠 1 秒钟
    					Thread.sleep(1000);
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				} 
    
    				System.out.println("线程:" + Thread.currentThread().getName() + ",count = " + count);
    			} finally {
    				semaphore.release(); 	// 释放当前线程的“锁”
    //				lock.unlock();
    			}
    			
    		}
    	}
    
    }
    

      

  • 相关阅读:
    5.1重磅活动:区块链免费送书
    Java 9 被无情抛弃,Java 8 直接升级到 Java 10!!
    Linux负载均衡利器(LVS)
    豌豆荚Redis集群方案:Codis
    Spring Boot Redis Cluster实战
    高性能代理缓存服务器—Squid
    Facebook分布式框架—Thrift介绍。
    Java 高级面试知识点汇总!
    (4)设计模式-建造者模式
    (3)设计模式-单例模式
  • 原文地址:https://www.cnblogs.com/hapday/p/6291086.html
Copyright © 2011-2022 走看看