Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.HashSet;
- import java.util.concurrent.Semaphore;
- public class KindergartenShow {
- public static class Child extends Thread
- {
- private static Semaphore seats=new Semaphore(6);
- private static Semaphore canPlay=new Semaphore(0);
- private static Semaphore lock=new Semaphore(1);
- private static Semaphore newCycle=new Semaphore(0);
- int groupNo=0;
- int totalNo=0;
- int sumPermits=0;
- int numExecutions=0;
- int sumQueue=0;
- public Child (int numRuns)
- {
- super(String.valueOf(numRuns));
- }
- public void execute () throws InterruptedException
- {
- seats.acquire();
- System.out.println("dete vleze");
- lock.acquire();
- groupNo++;
- if(groupNo==6)
- {
- canPlay.release(6);
- System.out.println("Pretstavata pocinja");
- }
- lock.release();
- canPlay.acquire(); // ova go vide
- lock.acquire();
- groupNo--; // ova go vide
- System.out.println("dete iskoci");
- totalNo++; // ova go vide
- if(groupNo==0)
- {
- seats.release(6); //cycleov go vide
- System.out.println("si idat decata");
- }
- //lock.release(); ova go napisa a ne treba
- if(totalNo==24)
- {
- newCycle.release(24);
- System.out.println("zavrsi cel ciklus");
- totalNo=0;
- }
- lock.release();
- newCycle.acquire();
- }
- }
- public static void main(String [] args) throws InterruptedException {
- HashSet<Child> threads = new HashSet<>();
- for(int i=0;i<24;i++)
- {
- Child c=new Child(i);
- threads.add(c);
- }
- for(Child c: threads)
- {
- c.start();
- }
- for(Child c: threads)
- {
- c.join(2000);
- }
- for (Child c: threads)
- {
- if(c.isAlive())
- {
- c.interrupt();
- System.out.println("Possible deadlock");
- }
- }
- System.out.println("Pretstavata zavrsi");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement