Multi-threaded concurrent Semaphore applications


/*
The Semaphonre object of a single semaphore can implement the function of a mutex,
And it can be that one thread acquires the "lock" and another thread releases the "lock"
This can be used in some cases of deadlock recovery. */

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); //Only 3 threads are allowed,
      for(int i=0;i<10;i++){ //10 tasks
        Runnable runnable = new Runnable(){
              public void run(){
              try{
                 sp.acquire(); //block
              } catch (InterruptedException e1) {
                 e1.printStackTrace();
              }
              System.out.println("线程" + Thread.currentThread().getName() +
                    "Enter, there are currently" + (3-sp.availablePermits()) + "concurrent");
              try{
                 Thread.sleep((long)(Math.random()*10000));
              }catch (InterruptedException e) {
                 e.printStackTrace ();
              }
              System.out.println("线程" + Thread.currentThread().getName() +
                    "about to leave");             
              sp.release(); //release
              //The following code sometimes executes inaccurately because it does not synthesize atomic units with the above code
              System.out.println("线程" + Thread.currentThread().getName() +
              "left, currently available" + (3-sp.availablePermits()) + "concurrent");             
           }
        };
        service.execute(runnable);       
      }
   }
}


Guess you like

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