/** Run the bollie thread */ @Override public void run() { golfBall[] ballsCollected; // Array to hold the balls bollie collects while (done.get() != true) { // Check that Range has not closed try { sleep(waitTime.nextInt(5000) + 2000); // Sleep for 2-7 seconds if (done.get() != true) { // Recheck condition for closing, just in case! bollieOnField.set(true); // Set Atomic boolean to true System.out.println("*********** Bollie collecting balls ************"); ballsCollected = sharedField .collectAllBallsFromField(); // Collect balls, no golfers allowed to swing while // this is happening semaphore.drainPermits(); // drain permits so that golfers must wait System.out.println( "*********** Bollie collected " + ballsCollected.length + " balls ************"); sleep(1000); // Simulate collecting and adding sharedStash.addBallsToStash(ballsCollected); // Add collected balls to stash semaphore.release( noGolfers); // Release semaphore and all waiting threads, so that golfers waiting can // continue to their next swing bollieOnField.set(false); // Set Atomic boolean to false, condition no longer blocked } } catch (InterruptedException e) { e.printStackTrace(); } } sharedStash.golfersGo(); }
public synchronized void run() { // Create a bucket for the collection of ball golfBall[] ballsCollected = new golfBall[sharedStash.getSizeStash()]; // Collect balls if the the Club is not closing do { try { sleep(waitTime.nextInt(1000)); System.out.println("*********** Bollie collecting balls ************"); // collect balls, no golfers allowed to swing while this is happening Golfer.setCart(new AtomicBoolean(true)); // count the number of balls collected int k = sharedField.collectAllBallsFromField(ballsCollected); System.out.println("*********** Bollie collected " + k + " balls from range ************"); sleep(1000); // bollie leave the range, golfer can swing Golfer.setCart(new AtomicBoolean(false)); // add balls to stash sharedStash.addBallsToStash(ballsCollected, k); System.out.println( "*********** Bollie adding " + k + " balls to stash (" + sharedStash.getBallsInStash() + " ball(s) in stash)************"); } catch (InterruptedException e) { e.printStackTrace(); } } while (done.get() != true); }