Skip to content

Instantly share code, notes, and snippets.

@boileryao
Created November 26, 2019 06:20
Show Gist options
  • Save boileryao/6c308f347ad533897f73023348ce8497 to your computer and use it in GitHub Desktop.
Save boileryao/6c308f347ad533897f73023348ce8497 to your computer and use it in GitHub Desktop.
Semaphore Sample
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);
}
}
@boileryao
Copy link
Author

One of possible output:

Person[2] in, seems has slots
Person[2] using
Person[6] in, seems has slots
Person[6] using
Person[3] in, seems has slots
Person[5] in, seems has slots
Person[4] in, seems has slots
Person[1] in, seems has slots
Person[7] in, seems NO slots
Person[8] in, seems NO slots
Person[9] in, seems NO slots
Person[10] in, seems NO slots
Person[2] complete using
Person[3] using
Person[6] complete using
Person[5] using
Person[5] complete using
Person[4] using
Person[3] complete using
Person[1] using
Person[4] complete using
Person[7] using
Person[7] complete using
Person[8] using
Person[1] complete using
Person[9] using
Person[8] complete using
Person[10] using
Person[10] complete using
Person[9] complete using
Everybody has been satisfied

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment