Guest User

Untitled

a guest
Jun 25th, 2018
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.32 KB | None | 0 0
  1. package you;
  2.  
  3. import clowns.Clown;
  4. import clowns.Volkswagen;
  5.  
  6. import java.util.ArrayList;
  7. import java.util.List;
  8.  
  9.  
  10. /**
  11.  * @author Sebastien Lorber <i>(lorber.sebastien@gmail.com)</i>
  12.  */
  13. public class You {
  14.  
  15.  
  16.     private static void sleep(int millies) {
  17.         try {
  18.             Thread.sleep(millies);
  19.         } catch (InterruptedException e) {
  20.             throw new RuntimeException(e);
  21.         }
  22.     }
  23.  
  24.  
  25.     public static final Volkswagen vw = new Volkswagen();
  26.  
  27.     public static int clownsInHashCode = 0;
  28.  
  29.  
  30.     public static void main(String args[]) {
  31.  
  32.         List<Clown> clownsList = new ArrayList<Clown>();
  33.  
  34.         for (int i = 0; i < 20; i++) {
  35.             final int clownIndex = i;
  36.             Clown clown =  new Clown() {
  37.                 @Override
  38.                 public int hashCode() {
  39.                     clownsInHashCode++;
  40.                     while ( clownsInHashCode != 20 ) {
  41.                         synchronized ( vw ) {
  42.                             try {
  43.                                 vw.wait(5000);
  44.                             } catch (InterruptedException e) { }
  45.                         }
  46.                     }
  47.                     synchronized ( vw ) {
  48.                         vw.notifyAll();
  49.                     }
  50.                     return super.hashCode();
  51.                 }
  52.                 @Override
  53.                 public String toString() {
  54.                     return ""+clownIndex;
  55.                 }
  56.             };
  57.             clownsList.add(clown);
  58.         }
  59.  
  60.  
  61.         for ( Clown clown : clownsList ) {
  62.             final Clown tempClown = clown;
  63.             Thread thread = new Thread( new Runnable() {
  64.                 public void run() {
  65.                     synchronized ( vw ) {
  66.                         System.out.println("Starting new thread");
  67.                         vw.add( tempClown );
  68.                     }
  69.                 }
  70.             });
  71.             thread.start();
  72.         }
  73.  
  74.        
  75.         while ( clownsInHashCode != 20 ) {
  76.             System.out.println("Only " + clownsInHashCode + " clowns waiting in the add method, need to wait a little bit more");
  77.             sleep(100);
  78.         }
  79.         System.out.println("All clown are actually inside the Set.add method but the set size is not incremented yet");
  80.         vw.done();
  81.     }
  82.    
  83.  
  84. }
Add Comment
Please, Sign In to add comment