Semaphore use and concurrent programming Detailed

The basic use of the class Semaphore

Semaphore's role: to limit the number of concurrent threads

Extra-curricular topic [multithreading] synchronization concept: in fact, lined up to perform a task, a mission is a execution advantage is help program logic correctness, does not appear non-thread-safety issues, the guarantor Runtime functionalities of stability.

FIG Semaphore class structure:

1, the class constructor permits Semaphore is permissive sense, represent the same time, permits a maximum of code execution between () Acquire () and release.
E.g:

Semaphore semaphore = new Semaphore(1);

It represents at most only one thread executes the same time acquire () between the code and the release ().
2, method acquire (n) function is invoked once per this method, it is consumed n licenses.
3. The method of release (n) function is invoked once per this method, it is dynamically added n licenses.
4. The method acquireUnnterruptibly () function is to be thread waiting to enter the acquire () method is not allowed to be interrupted.
5, the method availablePermits () Returns the number of licenses currently Semaphore object can be used.
6, the method drainPermits () Get and return all license number, and the license is reset to 0 available
7 getQueueLength method of action () is permitted to obtain the number of waiting threads
8, the method hasQueueThreads () action is there is no judgment of threads waiting for this license
9, equity and non-equity semaphore:
sometimes order to obtain licenses and order the thread startup, which is the amount of signal will be divided into equity and non-equity. The so-called fair amount of signal sequence and order to acquire a lock thread startup, but it does not mean 100 percent to get the semaphore, only in the probability guarantee, rather than the fair semaphore is irrelevant.
E.g:

Semaphore semaphore = new Semaphore(1false);

False:表示非公平信号量,即线程启动的顺序与调用semaphore.acquire() 的顺序无关,也就是线程先启动了并不代表先获得 许可。
True:公平信号量,即线程启动的顺序与调用semaphore.acquire() 的顺序有关,也就是先启动的线程优先获得许可
10、方法tryAcquire() 的作用是尝试获取1个许可。如果获取不到则返回false,通常与if语句结合使用,其具有无阻塞的特点。无阻塞的特点可以使不至于在同步处于一直持续等待的状态。
11、方法tryAcquire(n) 的作用是尝试获取n个许可,如果获取不到则返回false
12、方法tryAcquire(long timeout,TimeUnit unit)的作用是在指定的时间内尝试获取1个许可,如果获取不到则返回false
13、方法tryAcquire(int permits,long timeout,TimeUnit unit) 的作用是在指定的时间内尝试获取n 个许可,如果获取不到则返回false
14、多进路-多处理-多出路:允许多个线程同时处理任务
例如:

public class MyService {
    
    private Semaphore semaphore = new Semaphore(3);
    private Lock lock = new ReentrantLock();
    
    public void testMethod(){
        try
        {
            semaphore.acquire();
            //synchronized (this) 
            //{
                //lock.lock();
                System.out.println(Thread.currentThread().getName()+" 开始时间:"+System.currentTimeMillis());
                for(int i = 0; i < 10; i++){
                    System.out.println(Thread.currentThread().getName()+"打印"+ (i+1)+"");
                }
                System.out.println(Thread.currentThread().getName()+" 结束时间: "+System.currentTimeMillis());
                //lock.unlock();
            //}
            
            semaphore.release();
        }
        catch(Exception e)
        {
            
        }
    }
}

运行的效果是多个线程同时进入。并且多个线程有几乎同时执行完毕。

15、多进路-单处理-多出路:允许多个线程同时处理任务,但是顺序却是同步的,也就是阻塞的。所以也称单处理。

例如:在代码中加入ReentrantLock对象 ,或者使用synchronized 代码块,保存代码的同步性

public class MyService {
    
    private Semaphore semaphore = new Semaphore(3);
    private Lock lock = new ReentrantLock();
    
    public void testMethod(){
        try
        {
            semaphore.acquire();
            synchronized (this) 
            {
                //lock.lock();
                System.out.println(Thread.currentThread().getName()+" 开始时间:"+System.currentTimeMillis());
                for(int i = 0; i < 10; i++){
                    System.out.println(Thread.currentThread().getName()+"打印"+ (i+1)+"");
                }
                System.out.println(Thread.currentThread().getName()+" 结束时间: "+System.currentTimeMillis());
                //lock.unlock();
            }
            semaphore.release();
        }
        catch(Exception e)
        {    
        }
    }
}

1.2Exchanger的使用

作用:可以是2个线程之间传输数据

1、 方法exchange() 方法具有阻塞的特色,也就是此方法被调用后等待其他线程来取得数据,如果没有,则一直等待。

 

 

Guess you like

Origin www.cnblogs.com/wujiaofen/p/11356436.html