JAVA中的并发工具类(一)----控制并发数的Semaphore

来源:互联网 发布:初级php开发工程师 编辑:程序博客网 时间:2024/06/01 08:57

本文使用的Demo可以在我的github中找到。
前面我们使用线程池技术来控制访问资源的线程数目,假设对某一文件的访问,我们允许几十个线程来读他,但是出于某种限制,我们要求只允许10个线程可以同时读该文件。这就好比十字路口有100辆车想要过马路,我们只允许其中的10辆车可以看到绿灯然后让他们通过马路。Semaphore就类似于这种情境下的红绿灯。

Semaphore的应用场景:可以用于做流量控制,特别是共用资源有限的应用场景,比如数据库连接。几十个线程要求访问数据库,但是我们只提供10个连接数,这个时候,我们可以使用Semaphore来做流量控制。

示例Demo:

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 service = Executors.newCachedThreadPool();      // 规定一个线程池        final Semaphore sp = new Semaphore(3);                          // 允许最大并发数为3        for (int i = 0; i < 10; i++)        {                                                               // 开启十个线程。            Runnable runnable = new Runnable()            {                public void run()                {                    try                    {                        sp.acquire();                    } catch (InterruptedException e1)                    {                        e1.printStackTrace();                    }                    System.out.println(                            "线程" + Thread.currentThread().getName() + "进入,当前已有" + (3 - sp.availablePermits()) + "个并发");                    try                    {                        Thread.sleep((long) (Math.random() * 10000));                    } catch (InterruptedException e)                    {                        e.printStackTrace();                    }                    System.out.println("线程" + Thread.currentThread().getName() + "即将离开");                    sp.release();                    // 下面代码有时候执行不准确,因为其没有和上面的代码合成原子单元                    System.out.println(                            "线程" + Thread.currentThread().getName() + "已离开,当前已有" + (3 - sp.availablePermits()) + "个并发");                }            };            service.execute(runnable);        }        service.shutdown();    }}

运行结果如下:

线程pool-1-thread-2进入,当前已有3个并发线程pool-1-thread-1进入,当前已有3个并发线程pool-1-thread-3进入,当前已有3个并发线程pool-1-thread-1即将离开线程pool-1-thread-1已离开,当前已有3个并发线程pool-1-thread-4进入,当前已有3个并发线程pool-1-thread-4即将离开线程pool-1-thread-4已离开,当前已有2个并发线程pool-1-thread-5进入,当前已有3个并发线程pool-1-thread-5即将离开线程pool-1-thread-5已离开,当前已有2个并发线程pool-1-thread-7进入,当前已有3个并发线程pool-1-thread-3即将离开线程pool-1-thread-3已离开,当前已有2个并发线程pool-1-thread-8进入,当前已有3个并发线程pool-1-thread-2即将离开线程pool-1-thread-2已离开,当前已有2个并发线程pool-1-thread-10进入,当前已有3个并发线程pool-1-thread-8即将离开线程pool-1-thread-6进入,当前已有3个并发线程pool-1-thread-8已离开,当前已有3个并发线程pool-1-thread-6即将离开线程pool-1-thread-6已离开,当前已有2个并发线程pool-1-thread-9进入,当前已有3个并发线程pool-1-thread-9即将离开线程pool-1-thread-9已离开,当前已有2个并发线程pool-1-thread-7即将离开线程pool-1-thread-7已离开,当前已有1个并发线程pool-1-thread-10即将离开线程pool-1-thread-10已离开,当前已有0个并发
0 0
原创粉丝点击