Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8723377
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T07:36:45+00:00 2026-06-13T07:36:45+00:00

This program will generate n-LIZARD threads and 1 CAT thread. Upon waking up the

  • 0

This program will generate n-LIZARD threads and 1 CAT thread.
Upon “waking up” the LIZARD threads must perform a task “eat”. The lizards must cross from a Sago palm to the Monkey Grass to “eat” and then cross back. The cat thread will wake up after a given time then check to make sure there is no more than 4 LIZARD threads “crossing” at once. The idea is to let the “world” or program run until a given time of 120 seconds has passed and have the lizards protected from the cat.

I know little about the semaphore class and was wondering on how to implement and place a mutuel exclusion, and a regular semaphore. To control the threads in this program using .acquire() and .release().

I know that mutual exclusion will acquire one thread only ( so I was thinking this can be used to control the cat thread (let me know if im wrong)

So my regular semaphore must protect the “crossways”.

I have the idea down i just need some help with placement. I commented everything out so you all can be clear on what im trying (failing) to do 🙂

import java.util.ArrayList;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 */
public class LizardsSync 
{
    /*
     * Set this to the number of seconds you want the lizard world to
     * be simulated.  
     * Try 30 for development and 120 for more thorough testing.
     */
    private static int WORLDEND = 120;

    /*
     * Number of lizard threads to create
     */
    private static int NUM_LIZARDS =20;

    /*  
     * Maximum lizards crossing at once before alerting cats
     */
    private static int MAX_LIZARD_CROSSING = 4;

    /*
     * Maximum seconds for a lizard to sleep
     */
    private static int MAX_LIZARD_SLEEP_TIME = 3;

    /*
     * Maximum seconds for a lizard to eat
     */
    private static int MAX_LIZARD_EAT_TIME = 5;

    /*
     * Number of seconds it takes to cross the driveway
     */
    private static int CROSS_TIME = 2;

    /*
     * Number of seconds for the cat to sleep.
     */
    private static int MAX_CAT_SLEEP;

    /*
     * A counter that counts the number of lizzards crossing sago to monkey grass
     */
    int numCrossingSago2MonkeyGrass = 0;

    /*
     * A counter that counts the number of lizzards crossing monkey grass to sago
     */
    int numCrossingMonkeyGrass2Sago = 0;

    /**
     * A semaphore to protect the crossway. 

    */
    Semaphore semaphoreCrossway = new Semaphore(MAX_LIZARD_CROSSING);

    /**
     * A semaphore for mutual exclusion.
     */
    Semaphore mutex = new Semaphore(1);

    // on both semaphores, you can call acquire() or release()
    /*
     * Indicates if the world is still running.
     */
    private static boolean running = true;

    /*
     * Indicates if you want to see debug information or not.
     */
    private static boolean debug = true;


    public void go()
    {
        ArrayList<Thread> allThreads = new ArrayList<Thread>();

        // create all the lizzard threads
        for (int i=0; i < NUM_LIZARDS; i++) 
        {       allThreads.add(new LizardThread(i) );
            allThreads.get(i).start();
}
        // create the cat thread
        Thread CatThread = new CatThread();
         CatThread.start();

        // let the world run for a while
        sleep (WORLDEND);

        // terminate all threads
        running = false;
        // wait until all threads terminate by joining all of them
        for (int i=0; i < NUM_LIZARDS; i++) {
            try {
               allThreads.get(i).join();
            } catch (InterruptedException ex) {
                System.err.println ("unable to join thread, " + ex.getMessage());
            }
        }
    }
       /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // starts the program
        new LizardsSync().go();
    }

     /**
     * Models a cat thread.
     */
    public class CatThread extends Thread {


        /**
         * @see java.lang.Runnable.
         */
        @Override
        public void run() 
        {   
            while (running) {


                   // sleep for a while
                   catSleep();
                   // check on lizzards

                   checkCrossway();

            }
        }

        /**
         * Puts cat thread to sleep for a random time.
         */
        public void catSleep()
        {
            int sleepSeconds  = 1 + (int)(Math.random()*MAX_CAT_SLEEP);

            if (debug) {
                System.out.println ("Cat is sleeping for " + sleepSeconds + " seconds.");
                System.out.flush();
            }
            try {
                sleep(sleepSeconds*1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(LizardsSync.class.getName()).log(Level.SEVERE, null, ex);
            }

            if (debug) {
                System.out.println ("Cat awakes.");
                System.out.flush();
            }
        }

        /**
         * Simulates cat checking the crossway.
         */
        public void checkCrossway()
        {

            if (numCrossingMonkeyGrass2Sago + numCrossingSago2MonkeyGrass > MAX_LIZARD_CROSSING) {
                System.out.println ("The cat says yum!");
                System.out.flush();
                     System.exit(-1);
            }
       }
    }

    /**
     * Models a lizard thread.
     */
    public class LizardThread extends Thread {

        private int _id;

        /**
         * Creates a new lizard thread.
         * 
         * @param id the id assigned to the lizard thread
         */
        public LizardThread(int id)
        {
            _id = id;
        }

        /**
         * @see java.lang.Runnable.
         */
        @Override
        public void run() 
        {    

            while (running) {
               // sleep for a while in sago
               lizardSleep();
               // wait until safe to cross from sago to monkey grass
               sagoToMonkeyIsSafe();
               // cross path to monkey grass
               crossedOverToMonkey();
               // eat in the monkey grass
               lizardEat();
               // wait untill its safe to cross back to sago
               monkeyToSagoIsSafe();
               // cross from cross monkey grass to sage
               crossMonkeyToSago();
            }
        }

        /**
         * This tests if it is safe to travel from sago to monkey.
         * 
         */
        public void sagoToMonkeyIsSafe() 
        {

                if (debug) {
                    System.out.println ("Lizard [" + _id + "] checks sago -> monkey grass.");
                    System.out.flush();
                }



                if (debug) {
                    System.out.println ("Lizard [" + _id + "] thinks sago -> monkey grass is safe.");
                    System.out.flush();
                }


        }

        /**
         * Indicates that lizard crossed over to monkey grass.
         */
        public void crossedOverToMonkey()
        {
            if (debug) {
                System.out.println ("Lizard [" + _id + "] made it to monkey grass.");
                System.out.flush();
            }

           if (debug) {
                System.out.println ("Lizard [" + _id + "] thinks monkey grass -> sago is safe.");
                System.out.flush();

            }
        }


        /**
         * This tests if it is safe to travel from monkey to sago.
         */
        public void monkeyToSagoIsSafe() 
        {

            if (debug) {
                System.out.println ("Lizard [" + _id + "] checks monkey grass -> sago.");
                System.out.flush();
            }



            if (debug) {
                System.out.println ("Lizard [" + _id + "] thinks monkey grass -> sago is safe.");
                System.out.flush();

            }
        }

        /**
         * Indicates that lizard crossed over to sago.
         */
        public void crossedOverToSago()
        {
            if (debug) {
                System.out.println ("Lizard [" + _id + "] made it to sago.");
                System.out.flush();
            }

            if (debug) {
                System.out.println ("Lizard [" + _id + "] thinks sago -> monkey grass is safe.");
                System.out.flush();
        }
        }
        /**
         * Indicates that lizard is crossing over from monkey to sago.
         */
        void crossMonkeyToSago()
        {
            if (debug) {
                System.out.println ("Lizard [" + _id + "] is crossing monkey grass to sago.");
                System.out.flush();
            }

            numCrossingMonkeyGrass2Sago++;

            // simulate walk
            try {
                sleep(CROSS_TIME*1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(LizardsSync.class.getName()).log(Level.SEVERE, null, ex);
            }

            numCrossingMonkeyGrass2Sago--;
        }

        /**
         * Indicates that lizard is crossing over from sago to monkey. 
         */
        void crossSagoToMonkey()
        {

            if (debug) {
                System.out.println ("Lizard [" + _id + "] is crossing sago to monkey grass.");
                System.out.flush();
            }

            numCrossingSago2MonkeyGrass++;

            // simulate walk
            try {
                sleep(CROSS_TIME*1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(LizardsSync.class.getName()).log(Level.SEVERE, null, ex);
            }

            numCrossingSago2MonkeyGrass--;
        }


        /**
         * Puts lizard thread to sleep for a random amount of time.
         */
        public void lizardSleep()
        {
            int sleepSeconds  = 1 + (int)(Math.random()*MAX_LIZARD_SLEEP_TIME);

            if (debug) {
                System.out.println ("Lizard [" + _id + "] is sleeping for " + sleepSeconds + " seconds.");
                System.out.flush();
            }
            try {
                sleep(sleepSeconds*1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(LizardsSync.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (debug) {
                System.out.println ("Lizard [" + _id + "] awakes.");
                System.out.flush();
            }
        }

        /**
         * Simulates lizard eating for a random amount of time.
         */
        public void lizardEat()
        {
            int eatSeconds  = 1 + (int)(Math.random()*MAX_LIZARD_EAT_TIME);

            if (debug) {
                System.out.println ("Lizard [" + _id + "] is eating for " + eatSeconds + " seconds.");
                System.out.flush();
            }
            try {
                sleep(eatSeconds*1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(LizardsSync.class.getName()).log(Level.SEVERE, null, ex);
            }
            if (debug) {
                System.out.println ("Lizard [" + _id + "] finished eating.");
                System.out.flush();
            }
        }
    }


    /**
     * Puts current thread to sleep for a specified amount of time.
     * 
     * @param seconds the number of seconds to put the thread to sleep
     */
    private static void sleep(int seconds)
    {
        try {
            Thread.sleep(seconds*1000);
        } catch (InterruptedException ex) {
            Logger.getLogger(LizardsSync.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T07:36:46+00:00Added an answer on June 13, 2026 at 7:36 am

    Whenever you have to cross path you will call acquire and whenever you have crossed path you can call release

    Semaphore semaphore= new Semaphore(No of Lizards that can cross the road at a time);
    
    
    sagoToMonkeyIsSafe();<-- semaphore.acquire(); as crossing the path start
     // cross path to monkey grass
    crossedOverToMonkey();<---semaphore.release(); as crossing the path end
    
    monkeyToSagoIsSafe();<-- semaphore.acquire(); as crossing the path start
    // cross from cross monkey grass to sage
    crossMonkeyToSago();<---semaphore.release();  as crossing the path end
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm currently developing a program that will generate reports based upon lead data. My
This program is meant to generate a dynamic array, however it gives an access
This is the general goal I am trying to achieve: My VB.NET program will
I'm working on a program which will generate some temporary files, wait for the
I'm now going to develop a program that will generate Shell Batch Files(*.sh), but
How can I write a program that will automatically generate a sample examination? For
Making a simple program which will generate a multiple choice form. I have an
I'm attempting to write a program that will generate a text file with every
We are planning to implement a simulator generator program that will generate C# solution.
I want to develop a Java desktop application . This appliation will generate word

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.