Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.49 KB | None | 0 0
  1. /* ESEMPIO LOTTERIA */
  2.  
  3. /* Classe Giocatore */
  4.  
  5.  
  6. public class Giocatore extends Thread {
  7.  
  8.     private Lotteria l;
  9.     private int p;
  10.  
  11.     public Giocatore(Lotteria l, int p) {
  12.         this.l = l;
  13.         this.p = p;
  14.     }
  15.    
  16.     public void run() {
  17.         try {
  18.             Biglietto b = l.prendiNumero(p);
  19.             boolean ris = l.attendiEstrazione(new Biglietto[]{b});
  20.             System.out.println(ris?"Ho vinto":"Non ho vinto");
  21.         } catch(NumeroPresoException npe) {
  22.             System.out.println("Gia' preso");
  23.         } catch(InterruptedException ie) {
  24.             System.out.println("Interrotto");
  25.         }
  26.     }
  27. }
  28.  
  29. /* Classe Lotteria */
  30.  
  31.  
  32. public class Lotteria {
  33.  
  34.     private Biglietto[] numero;
  35.     private int venduti;
  36.     private Biglietto estratto;
  37.     private int n;
  38.  
  39.     public Lotteria(int n) {
  40.         numero = new Biglietto[n];
  41.         this.n = n;
  42.     }
  43.  
  44.     public synchronized Biglietto prendiNumero(int p) throws NumeroPresoException {
  45.         if(p<0 || p>=n)
  46.             throw new IllegalArgumentException();
  47.         if(numero[p] != null)
  48.             throw new NumeroPresoException();
  49.         Biglietto t = new Biglietto();
  50.         numero[p] = t;
  51.         venduti++;
  52.         return t;
  53.     }
  54.    
  55.     public synchronized boolean attendiEstrazione(Biglietto[] bb) throws InterruptedException {
  56.         if(venduti == n) {
  57.             estrai();
  58.             notifyAll();
  59.         }
  60.         while(venduti != n)
  61.             wait();
  62.         for(int i=0; i<bb.length; i++)
  63.             if(bb[i]==estratto)
  64.                 return true;
  65.         return false;  
  66.     }
  67.  
  68.     private void estrai() {
  69.         int t = (int)(Math.random()*n);
  70.         estratto = numero[t];
  71.     }
  72. }
  73.  
  74. /* Classe Biglietto */
  75.  
  76. public class Biglietto {
  77.  
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement