Created
November 24, 2021 12:05
-
-
Save y-fedorov/274e643f7cd10fef193241c59531b847 to your computer and use it in GitHub Desktop.
Java Semaphore App Example
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
package appstart.mymodappdemo; | |
import java.util.concurrent.Semaphore; | |
public class JavaSemaphoreApp { | |
public static void main(String[] args) { | |
Semaphore sem = new Semaphore(1); // how many times we can 'acquire' permission | |
CommonResource res = new CommonResource(); | |
new Thread(new CountThread(res, sem, "CountThread 1")).start(); | |
new Thread(new CountThread(res, sem, "CountThread 2")).start(); | |
new Thread(new CountThread(res, sem, "CountThread 3")).start(); | |
} | |
} | |
class CommonResource { | |
int x = 0; | |
} | |
class CountThread implements Runnable { | |
CommonResource res; | |
Semaphore sem; | |
String name; | |
CountThread(CommonResource res, Semaphore sem, String name) { | |
this.res = res; | |
this.sem = sem; | |
this.name = name; | |
} | |
public void run() { | |
try { | |
System.out.println(name + " await permission"); | |
sem.acquire(); | |
res.x = 1; | |
for (int i = 1; i < 5; i++) { | |
System.out.println(this.name + ": " + res.x); | |
res.x++; | |
Thread.sleep(100); | |
} | |
} catch (InterruptedException e) { | |
System.out.println(e.getMessage()); | |
} | |
System.out.println(name + " release permission"); | |
sem.release(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment