Java并发工具类(四)Semaphore

Java并发工具类(四)Semaphore

在J.U.C并发包中提供了一些工具类,可以供我们在日常的开发中,根据不同的情况去进行一些相关的并发控制,具体的类有:

CountDownLatch
Semaphore
Exchanger
CyclicBarrier

Exchanger

概念

semaphore是指信号量,是用来控制同时访问特定资源的线程总数,它通过协调各个线程,以保证合理的使用公共资源。

实现

  public static void main(String[] args) {  
        ExecutorService service = Executors.newCachedThreadPool();
        // 同时执行的线程数2
        final Semaphore semaphore = new Semaphore(2);
        final int count = 5;  
        for (int i = 0; i < count; i++) {  
            Runnable runnable = new Runnable() {  
                public void run() {  
                    try {  
                        semaphore.acquire();
                        System.out.println("线程:" + Thread.currentThread().getName()+"开始执行");  
                        Thread.sleep(1000);  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    } finally {  
                        System.out.println("线程:" + Thread.currentThread().getName() + "执行结束");  
                        semaphore.release();  
                    }  
                }  
            };  
            service.execute(runnable);
        }  
        service.shutdown();  
    }  

执行结果

线程:pool-1-thread-2开始执行
线程:pool-1-thread-1开始执行
线程:pool-1-thread-1执行结束
线程:pool-1-thread-4开始执行
线程:pool-1-thread-2执行结束
线程:pool-1-thread-3开始执行
线程:pool-1-thread-4执行结束
线程:pool-1-thread-5开始执行
线程:pool-1-thread-3执行结束
线程:pool-1-thread-5执行结束

Semaphore特性

Semaphore类的构造函数中传入的值,即为并发访问控制执行的线程数目。

完整代码和相关依赖请见GitHub

https://github.com/dwyanewede/project-learn/tree/master/src/main/java/com/learn/demo/concurrent

相关文章推荐

Java并发工具类(一)CountDownLatch https://blog.csdn.net/shang_xs/article/details/87075550
Java并发工具类(二)CyclicBarrier https://blog.csdn.net/shang_xs/article/details/87077098
Java并发工具类(三)Exchanger https://blog.csdn.net/shang_xs/article/details/87078321

猜你喜欢

转载自blog.csdn.net/shang_xs/article/details/87090443