Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.Semaphore;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class Main {
- public static void main(String[] args) {
- Brojac brojac = new Brojac();
- Brojac brojac2 = new Brojac();
- Brojac brojac3 = new Brojac();
- t t1 = new t(1, brojac);
- t t2 = new t(2, brojac);
- t t3 = new t(3, brojac);
- t1.start();
- t2.start();
- t3.start();
- try {
- t1.join();
- t2.join();
- t3.join();
- }
- catch (InterruptedException ex) {
- ex.printStackTrace();
- }
- System.out.println(brojac.getCnt());
- System.out.println(brojac2.getCnt());
- System.out.println(brojac3.getCnt());
- }
- }
- class t extends Thread {
- int id;
- static Brojac br;
- public t(int _id, Brojac br) {
- id = _id;
- this.br = br;
- }
- @Override
- public void run() {
- for(int i = 0; i < 20; i++) {
- try {
- br.zgolemi_brojac_semaphore();
- }
- catch (Exception ex) {
- }
- }
- }
- }
- class Brojac {
- private static int cnt = 0;
- private static Semaphore semaphore = new Semaphore(2);
- // public static void zgolemi_brojac() {
- // cnt++;
- // }
- public void zgolemi_brojac_semaphore() {
- try {
- semaphore.acquire();
- cnt++;
- semaphore.release();
- }
- catch (Exception e) {
- }
- }
- public static int getCnt() {
- return cnt;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement