Created
November 26, 2019 06:20
-
-
Save boileryao/6c308f347ad533897f73023348ce8497 to your computer and use it in GitHub Desktop.
Semaphore Sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.Semaphore; | |
public class SemaphorePersonThread extends Thread { | |
Semaphore position; | |
private int id; | |
public SemaphorePersonThread(int i, Semaphore s) { | |
this.id = i; | |
this.position = s; | |
} | |
public void run() { | |
try { | |
if (position.availablePermits() > 0) { | |
System.out.println("Person[" + this.id + "] in, seems has slots"); | |
} else { | |
System.out.println("Person[" + this.id + "] in, seems NO slots"); | |
} | |
position.acquire(); | |
System.out.println("Person[" + this.id + "] using"); | |
Thread.sleep((int) (10 + Math.random() * 800)); | |
System.out.println("Person[" + this.id + "] complete using"); | |
position.release(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
public static void main(String args[]) { | |
ExecutorService list = Executors.newCachedThreadPool(); | |
Semaphore position = new Semaphore(2); | |
for (int i = 0; i < 10; i++) { | |
list.submit(new SemaphorePersonThread(i + 1, position)); | |
} | |
list.shutdown(); | |
position.acquireUninterruptibly(2); | |
System.out.println("Everybody has been satisfied"); | |
position.release(2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One of possible output: