Advertisement
jovanovski

ОС Лаб8

May 14th, 2013
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.41 KB | None | 0 0
  1. import java.util.concurrent.Semaphore;
  2.  
  3. class domakin {
  4.     private final Semaphore semafor = new Semaphore(1);
  5.     int pocetenbroj;
  6.     int broj_na_lifcinja;
  7.    
  8.     domakin(int br) {
  9.         this.pocetenbroj = br;
  10.  
  11.     }
  12.  
  13.     public String toString() {
  14.         return "" + broj_na_lifcinja;
  15.     }
  16.    
  17.     public void staviLivcinja(){
  18.         broj_na_lifcinja = pocetenbroj;
  19.         System.out.println("Resetirav livcinja");
  20.     }
  21.    
  22.     public void sakamLifce() throws InterruptedException{
  23.         semafor.acquire();
  24.         izvadiLivce();
  25.     }
  26.    
  27.     public synchronized void izvadiLivce(){
  28.         broj_na_lifcinja--;
  29.         semafor.release();
  30.     }
  31.  
  32.  
  33. }
  34.  
  35. class ucesnik {
  36.  
  37.     String id;
  38.  
  39.     ucesnik(String id) {
  40.         this.id = id;
  41.     }
  42.  
  43.     public String toString() {
  44.         return id;
  45.     }
  46.  
  47.     //Edno resenie
  48.     public void zemiLivce(domakin dom){
  49.         dom.izvadiLivce();
  50.         System.out.println("Ucesnik " + id + " zema livce!");
  51.     }
  52.  
  53. }
  54.  
  55. public class lab8 {
  56.     public static void main(String[] args) {
  57.        
  58.         domakin dom = new domakin(3);
  59.         ucesnik u1 = new ucesnik("1");
  60.         ucesnik u2 = new ucesnik("2");
  61.         ucesnik u3 = new ucesnik("3");
  62.        
  63.        
  64.         while(true){
  65.             dom.staviLivcinja();
  66.             cekaj();
  67.             u1.zemiLivce(dom);
  68.             cekaj();
  69.             u2.zemiLivce(dom);
  70.             cekaj();
  71.             u3.zemiLivce(dom); 
  72.             cekaj();
  73.         }
  74.        
  75.        
  76.     }
  77.    
  78.     public static void cekaj(){
  79.         try {
  80.             Thread.sleep(500);
  81.         } catch (InterruptedException e) {
  82.             // TODO Auto-generated catch block
  83.             e.printStackTrace();
  84.         }
  85.     }
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement