Sample semaphore class with concurrent Java threads

  • 2020-04-01 02:49:11
  • OfStack


package com.yao;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class MySemaphore extends Thread {
 private int i;
 private Semaphore semaphore;

 public MySemaphore(int i,Semaphore semaphore){
  this.i = i;
  this.semaphore = semaphore;
 }

 public void run(){
  if(semaphore.availablePermits() > 0){
   System.out.println(""+i+" We have seats   :  ");
  }else{
   System.out.println(""+i+" Wait, there's no room  ");
  }
  try {
   semaphore.acquire();
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println(""+i+" Get space ");
  try {
   Thread.sleep((int)Math.random()*10000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  System.out.println(""+i+" After use ");
  semaphore.release();
 }
 public static void main(String[] args) {
  Semaphore semaphore = new Semaphore(2);
  ExecutorService service = Executors.newCachedThreadPool();
  for(int i = 0 ;i<10 ; i++){
   service.execute(new MySemaphore(i,semaphore));
  }
  service.shutdown();
  semaphore.acquireUninterruptibly(2);
  System.out.println(" After use, it needs to be cleaned "); 
  semaphore.release(2);
 }
}


Related articles: