Semaphore

 

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreTest {

	//If a factory has 5 machines, but there are 8 workers, a machine can only be used by one worker at the same time, only when it is used up,
	//Other workers can continue to use. Then we can do it through Semaphore
	 public static void main(String[] args) {
		 ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10);
		 int num = 5 ;
		 long start = System.currentTimeMillis();
		 Semaphore semaphore = new Semaphore(num);
		 for (int i = 0; i < 8; i++) {
			newFixedThreadPool.submit(new SemaphoreRunnable(semaphore));
		}
		 long end = System.currentTimeMillis();
		 newFixedThreadPool.shutdown();
		 
	 }

	 
	 public static class SemaphoreRunnable implements Runnable{
		private  Semaphore semaphore;
		 
		public SemaphoreRunnable(Semaphore semaphore) {
			this.semaphore = semaphore;
		}

		@Override
		public void run() {
			try {
				 long start = System.currentTimeMillis();
				 semaphore.acquire();
				 //Do some Thing
				 
				 Thread.sleep(1000);
				 semaphore.release();
				 long end = System.currentTimeMillis();
				 System.out.println(System.currentTimeMillis() +"=========" + (end-start)/1000);
			} catch (InterruptedException e) {
				e.printStackTrace ();
			}
		}
		 
	 }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

Donate to developers 

Driven by interest, I write 免费something with joy and sweat. I hope you like my work and can support it at the same time. Of course, if you have money to support a money field (support Alipay, WeChat, and the buckle group), if you have no money to support a personal field, thank you.

 

Personal homepage : http://knight-black-bob.iteye.com/



 
 
 Thank you for your sponsorship, I will do better!

 

Guess you like

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