Question

In: Computer Science

*OBJECT ORIENTED PROGRAMMING* JAVA PROGRAMMING GOAL: will be able to throw and catch exceptions and create...

*OBJECT ORIENTED PROGRAMMING*

JAVA PROGRAMMING

GOAL: will be able to throw and catch exceptions and create multi-threaded programs.

Part I

  • Create a class called Animal that implements the Runnable interface.
  • In the main method create 2 instances of the Animal class, one called rabbit and one called turtle. Make them "user" threads, as opposed to daemon threads.
  • Some detail about the Animal class. It has instance variables, name, position, speed, and restMax. It has a static boolean winner. It starts a false. The position represents the position in the race for this Animal object. The restMax represents how long the Animal rests between each time it runs.
  • The rabbit rests longer than the turtle, but the rabbit has a higher speed.
  • Let's make up some values to make this simulation more concrete.
  • The race is 100 yards. The initial position is 0. Suppose the speed of the rabbit is 5, and its maxRest is 150. Suppose the speed of the turtle is 3, and its maxRest is 100.
  • Adjust them so that the rabbit wins sometimes, and the turtle wins sometimes.
  • In the main method start both the rabbit and the turtle and see which one wins the races.
  • Here is the behavior of the run method in the Animal class.
  • Loop until the position is >= 100 or there is a winner. Each time through the loop, sleep() some random number of milliseconds. This random number will be between 0 and maxRest. Advance the position of the Animal by its speed.
  • Print who is running, what their position is, each time through the loop.
  • When someone wins, set the static variable winner to true, and both threads will finish their run method, and thus stop.
  • The winner is announced from inside the run method.

Part II

  • The objective here is to demonstrate the behavior of threads that share data, and use synchronized methods. You do not NOT use wait/ notify/ notifyAll in this exercise.
  • When the above race working, add to it in the following way.
  • Create a class called Food. It is not a Thread, and does not run. It's just a class that represents some data that will be shared by multiple threads.
  • Simulating an animal eating, simply means that the thread will sleep for some length of time. This is the same as the "resting" that the turtle an rabbit did in part I.
  • There is one instance of the Food class that is shared by both of the animals. Pass it to the constructor of the Animal class for both the turtle and the rabbit.
  • There is a method in the Food class called eat(). This method is synchronized, i.e., only one Animal can be eating at a time.
  • The rabbit eats the food (the thread will sleep) for a longer time than the turtle, thus giving an advantage to the turtle.
  • But, the turtle must wait until the rabbit is done eating until it can eat, so the advantage is reduced.
  • Print out the message inside the eat method when the animal begins to eat, and when it is done eating. Indicate which animal it is that starts to eat.
  • Try making the eat method not synchronized, and observe the different behavior if the eat method allows the rabbit to begin eating before the turtle is done eating.
  • *Note that this program will have in some cases exception handling. Make sure that all exceptions are handled according to standard programming practices.

Solutions

Expert Solution

Part 1 :

Animal.java

package com.company;

import java.util.Random;

public class Animal extends Food implements Runnable {

    private String name;
    private int position;
    private int speed;
    private  int restMax;
    public static boolean winner = false;

    public Animal(String name,int pos, int speed, int rest)
    {
        this.name = name;
        this.position =pos;
        this.speed = speed;
        this.restMax = rest;
    }

    @Override
    public void run() {
        try {
            while (position < 100 && !winner) {
                Random r = new Random();
                int time = r.nextInt(restMax);
                Thread.sleep(time);
                position = position + speed;
                System.out.println(name + " is running with speed " + speed + " and is at position " + position);
                if(position>=100){
                    winner =true;
                    System.out.println(name + " is winner.");
                    break;
                }

            }
        } catch (InterruptedException e){
            System.out.println(name + " interrupted.");
        }
    }
    
    public void start() {
        System.out.println(name + " starts to run.");
        Thread t;
        t = new Thread(this);
        t.start();

    }
}

Main.java

package com.company;

public class Main {

    public static void main(String[] args) {
   Animal rabbit = new Animal("rabbit",0,5,150);
   Animal turtle  = new Animal("turtle",0,3,100);
   rabbit.start();
   turtle.start();
    }
}

Output :

rabbit starts to run.
turtle starts to run.
rabbit is running with speed 5 and is at position 5
turtle is running with speed 3 and is at position 3
rabbit is running with speed 5 and is at position 10
turtle is running with speed 3 and is at position 6
rabbit is running with speed 5 and is at position 15
turtle is running with speed 3 and is at position 9
rabbit is running with speed 5 and is at position 20
turtle is running with speed 3 and is at position 12
turtle is running with speed 3 and is at position 15
turtle is running with speed 3 and is at position 18
rabbit is running with speed 5 and is at position 25
turtle is running with speed 3 and is at position 21
rabbit is running with speed 5 and is at position 30
turtle is running with speed 3 and is at position 24
rabbit is running with speed 5 and is at position 35
turtle is running with speed 3 and is at position 27
turtle is running with speed 3 and is at position 30
turtle is running with speed 3 and is at position 33
rabbit is running with speed 5 and is at position 40
turtle is running with speed 3 and is at position 36
rabbit is running with speed 5 and is at position 45
turtle is running with speed 3 and is at position 39
turtle is running with speed 3 and is at position 42
rabbit is running with speed 5 and is at position 50
turtle is running with speed 3 and is at position 45
turtle is running with speed 3 and is at position 48
rabbit is running with speed 5 and is at position 55
turtle is running with speed 3 and is at position 51
turtle is running with speed 3 and is at position 54
rabbit is running with speed 5 and is at position 60
rabbit is running with speed 5 and is at position 65
turtle is running with speed 3 and is at position 57
turtle is running with speed 3 and is at position 60
turtle is running with speed 3 and is at position 63
rabbit is running with speed 5 and is at position 70
turtle is running with speed 3 and is at position 66
rabbit is running with speed 5 and is at position 75
rabbit is running with speed 5 and is at position 80
turtle is running with speed 3 and is at position 69
turtle is running with speed 3 and is at position 72
rabbit is running with speed 5 and is at position 85
rabbit is running with speed 5 and is at position 90
turtle is running with speed 3 and is at position 75
rabbit is running with speed 5 and is at position 95
turtle is running with speed 3 and is at position 78
rabbit is running with speed 5 and is at position 100
rabbit is winner.

Process finished with exit code 0

Explanation :

Animal.java :

  • Animal Class has variable instances as name as String, position, speed,restMax as Integers, and one static boolean winner which is set to false. (at the start of the race)
  • Animal Class implements Runnable interface i.e. implementing run() and start() methods.
  • A parameterized constructor is also defined which takes all the instance variable except static variable winner and initialize them and instantiate an object.

void start() :

  • It tells that a particular animal has started (display the message)
  • Then, it creates an object of Thread and initializes it to own thread. (object itself as a thread)
  •   Then it simply starts that object.

void run() :

  • It initiates the loop to run unless there is a winner (winner ==true) or position >= 100 (completed the race)
  • It is inside the try block to test for sleep() method to cause any InterruptedException or not.
  • Then we have created a Random() generator r to make variable sleep time for each thread.
  • Then after resting the particular animal will run with its speed to update its position in the race.
  • We will display the current description of the animal who is running now.
  • If the position is equal to 100 or greater than 100, then the winner is decided, so winner = true and he is announced (i.e. printed on screen)

Main.java :

  • ​​​​​​​It creates two instances of animals namely rabbit and turtle by initializing with specified values.
  • Then, call the start() method to run Threads of animal classes.

Part 2 :

Food.java :

package com.company;

import java.util.Random;

public class Food {
    protected String food;

     synchronized protected void eat(String name,int rest) {
         try {
             Random r = new Random();
             int time = r.nextInt(rest);
             System.out.println(name + " start eating " + food );
             Thread.sleep(time);
         } catch (InterruptedException e) {
             System.out.println("Interrupted");
         }
     }
}

Animal.java :

package com.company;

import java.util.Random;

public class Animal extends Food implements Runnable {

    private String name;
    private int position;
    private int speed;
    private  int restMax;
    public static boolean winner = false;

    public Animal(String name,int pos, int speed, int rest,String food)
    {
        this.name = name;
        this.position =pos;
        this.speed = speed;
        this.restMax = rest;
        super.food = food;
    }


    public void run() {
        try {
            while (position <= 100 && !winner) {
                eat(name,restMax);

                position = position + speed;
                if(position>100){
                    winner =true;
                }
                System.out.println(name + " is running with speed " + speed + " and is at position " + position);
            }
            if(position>100){
                winner = true;
                System.out.println(name + " is winner.");
            }

        } catch (Exception e){
            System.out.println(name + " interrupted.");
        }
    }

    public void start() {
        System.out.println(name + " starts to run.");
        Thread t;
        t = new Thread(this,name);
        t.start();

    }
}

Main.java :

package com.company;

public class Main {

    public static void main(String[] args) {
   Animal rabbit = new Animal("rabbit",0,5,150,"fruits");
   Animal turtle  = new Animal("turtle",0,3,100,"grapes");
   rabbit.start();
   turtle.start();
    }
}

Output :

rabbit starts to run.
turtle starts to run.
rabbit start eating fruits
turtle start eating grapes
turtle is running with speed 3 and is at position 3
turtle start eating grapes
rabbit is running with speed 5 and is at position 5
rabbit start eating fruits
turtle is running with speed 3 and is at position 6
turtle start eating grapes
rabbit is running with speed 5 and is at position 10
rabbit start eating fruits
turtle is running with speed 3 and is at position 9
turtle start eating grapes
rabbit is running with speed 5 and is at position 15
rabbit start eating fruits
turtle is running with speed 3 and is at position 12
turtle start eating grapes
rabbit is running with speed 5 and is at position 20
rabbit start eating fruits
turtle is running with speed 3 and is at position 15
turtle start eating grapes
turtle is running with speed 3 and is at position 18
turtle start eating grapes
turtle is running with speed 3 and is at position 21
turtle start eating grapes
rabbit is running with speed 5 and is at position 25
rabbit start eating fruits
turtle is running with speed 3 and is at position 24
turtle start eating grapes
turtle is running with speed 3 and is at position 27
turtle start eating grapes
turtle is running with speed 3 and is at position 30
turtle start eating grapes
turtle is running with speed 3 and is at position 33
turtle start eating grapes
rabbit is running with speed 5 and is at position 30
rabbit start eating fruits
turtle is running with speed 3 and is at position 36
turtle start eating grapes
rabbit is running with speed 5 and is at position 35
rabbit start eating fruits
turtle is running with speed 3 and is at position 39
turtle start eating grapes
rabbit is running with speed 5 and is at position 40
rabbit start eating fruits
turtle is running with speed 3 and is at position 42
turtle start eating grapes
rabbit is running with speed 5 and is at position 45
rabbit start eating fruits
turtle is running with speed 3 and is at position 45
turtle start eating grapes
turtle is running with speed 3 and is at position 48
turtle start eating grapes
rabbit is running with speed 5 and is at position 50
rabbit start eating fruits
rabbit is running with speed 5 and is at position 55
rabbit start eating fruits
turtle is running with speed 3 and is at position 51
turtle start eating grapes
rabbit is running with speed 5 and is at position 60
rabbit start eating fruits
rabbit is running with speed 5 and is at position 65
rabbit start eating fruits
turtle is running with speed 3 and is at position 54
turtle start eating grapes
rabbit is running with speed 5 and is at position 70
rabbit start eating fruits
turtle is running with speed 3 and is at position 57
turtle start eating grapes
rabbit is running with speed 5 and is at position 75
rabbit start eating fruits
turtle is running with speed 3 and is at position 60
turtle start eating grapes
rabbit is running with speed 5 and is at position 80
rabbit start eating fruits
rabbit is running with speed 5 and is at position 85
rabbit start eating fruits
rabbit is running with speed 5 and is at position 90
rabbit start eating fruits
turtle is running with speed 3 and is at position 63
turtle start eating grapes
turtle is running with speed 3 and is at position 66
turtle start eating grapes
turtle is running with speed 3 and is at position 69
turtle start eating grapes
rabbit is running with speed 5 and is at position 95
rabbit start eating fruits
rabbit is running with speed 5 and is at position 100
rabbit start eating fruits
turtle is running with speed 3 and is at position 72
turtle start eating grapes
rabbit is running with speed 5 and is at position 105
rabbit is winner.
turtle is running with speed 3 and is at position 75

Process finished with exit code 0

Explanation :

Food.java :

  • It has an instance of food that is shared by the animal Class.

eat() :

  • It takes two parameters name of the animal and its resting time
  • It displays that a particular animal (name) starts eating its particular food (food).
  • As the animals rest during their eating, the whole Thread sleeping block statements are moved here from the run() method of Animal Class.
  • This method is synchronized i.e. No thread can start its eat method until the current thread's eat method has completely executed.
  • If the method was not synchronized, then both the animals were allowed to eat at any time without waiting for the current animal to complete eating.
  • In short, every animal has to wait for its turn to eat.

Main.java :

  • The constructor accepts one more value that is the type of food to initialize the food variable instance of Food Class.

Output without using non-synchronized eat() method :

rabbit starts to run.
turtle starts to run.
rabbit start eating fruits
turtle start eating grapes

turtle is running with speed 3 and is at position 3
turtle start eating grapes
rabbit is running with speed 5 and is at position 5
rabbit start eating fruits
rabbit is running with speed 5 and is at position 10
rabbit start eating fruits
turtle is running with speed 3 and is at position 6
turtle start eating grapes
turtle is running with speed 3 and is at position 9
turtle start eating grapes
turtle is running with speed 3 and is at position 12
turtle start eating grapes
rabbit is running with speed 5 and is at position 15
rabbit start eating fruits
turtle is running with speed 3 and is at position 15
turtle start eating grapes
turtle is running with speed 3 and is at position 18
turtle start eating grapes
turtle is running with speed 3 and is at position 21
turtle start eating grapes
turtle is running with speed 3 and is at position 24
turtle start eating grapes
rabbit is running with speed 5 and is at position 20
rabbit start eating fruits
turtle is running with speed 3 and is at position 27
turtle start eating grapes
turtle is running with speed 3 and is at position 30
rabbit is running with speed 5 and is at position 25
rabbit start eating fruits
turtle start eating grapes

turtle is running with speed 3 and is at position 33
turtle start eating grapes
turtle is running with speed 3 and is at position 36
turtle start eating grapes
turtle is running with speed 3 and is at position 39
turtle start eating grapes
rabbit is running with speed 5 and is at position 30
rabbit start eating fruits
turtle is running with speed 3 and is at position 42
turtle start eating grapes
turtle is running with speed 3 and is at position 45
turtle start eating grapes
rabbit is running with speed 5 and is at position 35
rabbit start eating fruits
turtle is running with speed 3 and is at position 48
turtle start eating grapes
rabbit is running with speed 5 and is at position 40
rabbit start eating fruits
turtle is running with speed 3 and is at position 51
turtle start eating grapes
rabbit is running with speed 5 and is at position 45
rabbit start eating fruits
turtle is running with speed 3 and is at position 54
turtle start eating grapes
rabbit is running with speed 5 and is at position 50
rabbit start eating fruits
turtle is running with speed 3 and is at position 57
turtle start eating grapes
turtle is running with speed 3 and is at position 60
turtle start eating grapes
rabbit is running with speed 5 and is at position 55
rabbit start eating fruits
turtle is running with speed 3 and is at position 63
turtle start eating grapes
turtle is running with speed 3 and is at position 66
turtle start eating grapes
turtle is running with speed 3 and is at position 69
turtle start eating grapes
rabbit is running with speed 5 and is at position 60
turtle is running with speed 3 and is at position 72
rabbit start eating fruits
turtle start eating grapes

rabbit is running with speed 5 and is at position 65
rabbit start eating fruits
turtle is running with speed 3 and is at position 75
turtle start eating grapes
rabbit is running with speed 5 and is at position 70
rabbit start eating fruits
turtle is running with speed 3 and is at position 78
turtle start eating grapes
turtle is running with speed 3 and is at position 81
turtle start eating grapes
turtle is running with speed 3 and is at position 84
turtle start eating grapes
rabbit is running with speed 5 and is at position 75
rabbit start eating fruits
turtle is running with speed 3 and is at position 87
turtle start eating grapes
turtle is running with speed 3 and is at position 90
rabbit is running with speed 5 and is at position 80
rabbit start eating fruits
turtle start eating grapes

turtle is running with speed 3 and is at position 93
turtle start eating grapes
rabbit is running with speed 5 and is at position 85
rabbit start eating fruits
turtle is running with speed 3 and is at position 96
turtle start eating grapes
rabbit is running with speed 5 and is at position 90
rabbit start eating fruits
turtle is running with speed 3 and is at position 99
turtle start eating grapes
turtle is running with speed 3 and is at position 102
turtle is winner.

Explanation: The Highlighted output shows animals do not wait for another animal to finish and start eating together.


Related Solutions

*OBJECT ORIENTED PROGRAMMING* GOAL: will be able to throw and catch exceptions and create multi-threaded programs....
*OBJECT ORIENTED PROGRAMMING* GOAL: will be able to throw and catch exceptions and create multi-threaded programs. Part I Create a class called Animal that implements the Runnable interface. In the main method create 2 instances of the Animal class, one called rabbit and one called turtle. Make them "user" threads, as opposed to daemon threads. Some detail about the Animal class. It has instance variables, name, position, speed, and restMax. It has a static boolean winner. It starts a false....
object oriented programming java Create a Student class that have two data members id (assign to...
object oriented programming java Create a Student class that have two data members id (assign to your ID) and name (assign to your name). Create the object of the Student class by new keyword and printing the objects value. You may name your object as Student1. The output should be like this: 20170500 Asma Zubaida
OBJECT-ORIENTED JAVA The catch-or-declare requirement states that you have two choices: You can either catch the...
OBJECT-ORIENTED JAVA The catch-or-declare requirement states that you have two choices: You can either catch the exception or you can provide a throws clause. To which exceptions does the catch-or-declare requirement apply? Errors All Exceptions except RuntimeExceptions RuntimeExceptions All Throwable except Errors Flag this Question Question 21 pts Assume you have an array called numbers. It's elements are of type int and it was declared like this: int[] numbers = { 3, 6, 9, 12 }; Assume that you also...
This week, you will create and implement an object-oriented programming design for your project. You will...
This week, you will create and implement an object-oriented programming design for your project. You will learn to identify and describe the classes, their attributes and operations, as well as the relations between the classes. Create class diagrams using Visual Studio. Review the How to: Add class diagrams to projects (Links to an external site.) page from Microsoft’s website; it will tell you how to install it. Submit a screen shot from Visual Studio with your explanation into a Word...
-What is object-oriented programming? -What is a class? -What is an object? -A contractor uses a...
-What is object-oriented programming? -What is a class? -What is an object? -A contractor uses a blueprint to build a set of identical houses. Are classes analogous to the blueprint or the houses? Explain. -What is a class diagram? How is it used in object-oriented programming? -What is an attribute in OOP? What is a data member? -What is a method in OOP? What is a member function? -What is the difference between private members and public members of a...
Object-Oriented Design and Patterns in Java (the 3rd Edition Chapter 5) - Create a directory named...
Object-Oriented Design and Patterns in Java (the 3rd Edition Chapter 5) - Create a directory named as the question number and save the required solutions in the directory. - Each problem comes with an expected tester name. In the directory for a given problem, including the tester and all java classes successfully run this tester. Exercise 5.2 ObserverTester.java - Improve Exercise 1 by making the graph view editable. Attach a mouse listener to the panel that paints the graph. When...
Briefly explain the terms used in object-oriented programming with examples.
Briefly explain the terms used in object-oriented programming with examples.
1. In Object Oriented Programming The private object fields can be directly manipulated by outside entities....
1. In Object Oriented Programming The private object fields can be directly manipulated by outside entities. Group of answer choices A. True B. False 2. __________ programming is centered on the procedures or actions that take place in a program. Group of answer choices A. Class B. Object-oriented C. Menu-driven D. Procedural/ Structural 3. __________ programming encapsulates data and functions in an object. Group of answer choices A. Object-oriented B. Class C. Menu-driven D. Procedural 4. The data in an...
Develop an object-oriented programming (OOP) application to create two clocks simultaneously displaying 12:00 and 24:00 format...
Develop an object-oriented programming (OOP) application to create two clocks simultaneously displaying 12:00 and 24:00 format and allow for user input using secure and efficient C++ code. Thank you!
Why is it more feasible to use Objects and object oriented programming as compared to using...
Why is it more feasible to use Objects and object oriented programming as compared to using method based programs? What are the disadvantages of using only methods in your programs.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT