Java concurrent synchronization auxiliary class semaphore

The meaning of semaphore (seməˌfôr): A

semaphore is the ability to declare multiple locks (including one lock: a mutex semaphore at this time).
For example: If a room can only accommodate 5 people, the extra people must wait outside the door. How to do it? One solution is: there are five keys hanging outside the room, and each person who enters will take one key away. Those who do not have a key cannot enter the room but wait outside. Every time a person comes out, put the key back to the original place so that others can enter again.



Common methods
acquire(): acquire the semaphore, the semaphore internal counter is decremented by 1
release(): release the semaphore, the semaphore internal counter is incremented by 1
tryAcquire(): this method tries to acquire the semaphore, if it can be acquired, it returns true, otherwise it returns false
The number of threads controlled by the semaphore is determined at declaration time. For example:
    Semphore s = new Semphore(2);
an example
to implement a function: a print queue, printed by three printers

package semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java. util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintQueue {
//Semaphore
    private Semaphore semaphore;
   
    //Is the printer idle
    private boolean freePrinters[];
   
    private Lock lockPrinters;
   
    public PrintQueue(){
    //Initialize three signals
        semaphore=new Semaphore(3);
        //Three idle printers
        freePrinters=new boolean[3 ];
        for (int i=0; i<3; i++){
            freePrinters[i]=true;
        }
        lockPrinters=new ReentrantLock();
    }
   
    public void printJob (Object document){
        try {
        //Get
            semaphore semaphore.acquire ();
           
            int assignedPrinter=getPrinter();
           
            Long duration=(long)(Math.random()*10);
            System.out.printf("%s: PrintQueue: Printing a Job in Printer %d during %d seconds\n",Thread.currentThread().getName(),assignedPrinter,duration);
            TimeUnit.SECONDS.sleep(duration);
           
            freePrinters[assignedPrinter]=true;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // Free the semaphore
            semaphore.release();           
        }
    }
    private int getPrinter() {
        int ret=-1;
       
        try {
            lockPrinters.lock();
            for (int i=0; i<freePrinters.length; i++) {
                if (freePrinters[i]){
                    ret=i;
                    freePrinters[i]=false;
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lockPrinters.unlock();
        }
        return ret;
    }
}

声明一个Job类,使用打印队列:
package semaphore;

public class Job implements Runnable {

     private PrintQueue printQueue;
     
      public Job(PrintQueue printQueue){
          this.printQueue=printQueue;
     }
     
      @Override
      public void run() {
         System.out.printf("%s: Going to print a job\n",Thread.currentThread().getName());
         printQueue.printJob(new Object());
         System.out.printf("%s: The document has been printed\n",Thread.currentThread().getName());       
     }
}

测试:
package semaphore;

public class MainCmd {
public static void main (String args[]){

PrintQueue printQueue=new PrintQueue();
//启动12个打印线程
        Thread thread[]=new Thread[12];
        for (int i=0; i<12; i++){
            thread[i]=new Thread(new Job(printQueue),"Thread "+i);
        }
        for (int i=0; i<12; i++){
            thread[i].start();
        }
} }
Points

to pay attention to
1. For the critical section declared by the semaphore, although the number of thread accesses can be controlled, it cannot guarantee that the code blocks are thread-safe. So the above example uses locks in the method printJob() to ensure data security.
2. The semaphore also involves the issue of fairness. As with lock fairness, this is unfair by default. The fairness of declaring locks can be displayed explicitly through the constructor.
public Semaphore(int permits, boolean fair)

application scenarios
Flow control, that is, controlling the maximum number of threads that can be accessed.

Mass video get vue video angular video

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326167588&siteId=291194637