1.

Write a program to simulate a simple traffic light at an intersection of two roads.

It will be easiest to view the example as four one-way roads, since cars can approach and pass through the intersection from four directions. Assign each road a number from 1 to 4.

Each time a car is at the intersection, request that the simple traffic light turn green. Implement a traffic light object with a turnGreen(int roadNumber) method. When a car is at the intersection it will call this method and pass its number. If road number 1 calls the turnGreen method, the method should print out:

      Light turned green by road 1
      Waiting for road 1 car to clear intersection
      10 9 8 7 6 5 4 3 2 1 0

Use a loop to print a countdown of the waiting period from 10 to 0.

Make each of the four roads a thread and fill the roads with 100 cars. A road is a simple queue. The first car in the road will call turnGreen and be removed. After a very short wait (perhaps 5 milliseconds), the next car in the road will call turnGreen, until the road is empty. Run the simulation.

Describe the output. Do any of the cars collide (i.e., are they in the intersection at the same time)?


Answer:


2.

Create an applet that uses threads to display bouncing balls in a panel.

Create a Ball class. A Ball is colored a random color. A Ball should be able to move relative to the panel it is in, and draw itself in the panel. To bounce a ball, choose the distance the ball will move in the x and y directions. These values can be represented as dx and dy. When a ball moves, dx and dy are added to the ball's x and y positions. For your program, dx and dy should both be greater than 0. You may choose the dx and dy to be equal to have the ball move at a constant slope of either plus or minus 1. When a ball reaches the edge of the panel it is in, you must reverse its direction by changing the sign of dx and/or dy.

The applet should have an "Add Ball" button. When the "Add Ball" button is pressed a new thread is created that moves and displays a new ball in the panel. Use the sleep() method to control the speed of the ball.


Answer:


3.

Create an applet that uses threads to display and interrupt bouncing balls on a panel. The threads are contained in a ThreadGroup.

Create a Ball class. A Ball is colored a random color. A Ball should be able to move relative to the panel it is in, and draw itself in the panel. To bounce a ball, choose the distance the ball will move in the x and y directions. These values can be represented as dx and dy. When a ball moves, dx and dy are added to the ball's x and y positions. For your program, dx and dy should both be greater than 0. You may choose the dx and dy to be equal to have the ball move at a constant slope of either plus or minus 1. When a ball reaches the edge of the panel it is in, you must reverse its direction by changing the sign of dx and/or dy.

The applet should contain two buttons, an "Add Ball" button and an "Interrupt Balls" button. When the "Add Ball" button is pressed a new thread is created that moves and displays a new ball in the panel. Use the sleep() method to control the speed of the ball. Remember to add the thread to a ThreadGroup.

When the "Interrupt Balls" button is pressed, the interrupt() method of the ThreadGroup is called. The balls should still be displayed on the screen, but should no longer move (Hint: Add the Balls, not the threads running the balls, to an array associated with your panel so your panel can draw them). Also, inside the threads that run the balls, make sure you check for isInterrupted() or not all the balls may stop.

Add two labels to the applet, one to keep track of the number of active balls (by calling the int activeCount() method of your ThreadGroup) and one to keep track of the number of balls on the panel.

Extra credit

If you run your simulation long enough, you might notice that after the balls are interrupted, the ball count is not always displayed as 0, even though all the balls have stopped moving. Why might this happen? Fix your code so that this does not happen.


Answer:


4.

Create an applet that uses threads with different priorities to display bouncing balls in a panel.

Create a Ball class. A Ball is colored a random color. A Ball should be able to move relative to the panel it is in, and draw itself in the panel. To bounce a ball, choose the distance the ball will move in the x and y directions. These values can be represented as dx and dy. When a ball moves, dx and dy are added to the ball's x and y positions. For your program, dx and dy should both be greater than 0. You may choose the dx and dy to be equal to have the ball move at a constant slope of either plus or minus 1. When a ball reaches the edge of the panel it is in, you must reverse its direction by changing the sign of dx and/or dy.

The applet should have an "Add Ball" button. When the "Add Ball" button is pressed a new thread is created that moves and displays a new ball in the panel.

Use the following code to assign priorities to the threads:

   int priorities[] = { Thread.MIN_PRIORITY, Thread.NORM_PRIORITY,
            Thread.MAX_PRIORITY };
   int pCount = 0;

   . . .

   currentPriority = priorities[pCount++ % 3];

Create the thread using the currentPriority. Every third ball should have the same priority.

Use the sleep() method to control the speed of the ball. All balls, independent of priority, should sleep for the same amount of time.


Answer:


5.

Modify your existing program or write a new program to simulate a simple traffic light at an intersection of two roads using a synchronized method.

It will be easiest to view the example as four one-way roads, since cars can approach and pass through the intersection from four directions. Assign each road a number from 1 to 4.

Each time a car is at the intersection, request that the simple traffic light turn green. Implement a traffic light object with a turnGreen(int roadNumber) method. Make your turnGreen method synchronized. When a car is at the intersection it will call this method and pass its number. If road number 1 calls the turnGreen method, the method should print out:

   Light turned green by road 1
    Waiting for road 1 car to clear intersection
    10 9 8 7 6 5 4 3 2 1 0

Use a loop to print a countdown of the waiting period from 10 to 0.

Make each of the four roads a thread and fill the roads with 100 cars. A road is a simple queue. The first car in the road will call turnGreen and be removed. After a very short wait (perhaps 5 milliseconds), the next car in the road will call turnGreen, until the road is empty. Run the simulation.

Describe the output. Do any of the cars collide (i.e., are they in the intersection at the same time)?

What happens when you remove the synchronized keyword?


Answer:


6.

Create a program that simulates a store's inventory.

A store carries varying quantities of five different items (your choice of items and amounts).

Five customers repeatedly generate random requests for multiple items and ask the store to fill the requests. If the store has enough items in inventory, it will fill the request, and subtract the quantities of the request from the inventory. If the store does not have enough items in inventory, the customer must wait for more inventory to arrive.

A store manager is in charge of ordering more items. The store manager will check to see if any of the items in inventory are depleted. If they are, he will order more items. However, the store manager has other things to do, so he doesn't constantly check the amounts in the inventory. He sleeps in between checks of the inventory.

Create a program to run this simulation. Implement customers and the store manager as threads. Make sure all appropriate methods are synchronized. Sample output from the program may look like:

. .
Store inventory
---------------
Apples: 44, Oranges: 29, Pineapples: 9, Persimmons: 43, Kumquats: 27
---------------  

Customer 4 requests, 1 Apple, 3 Oranges, 9 Pineapples, 0 Persimmons, 5 Kumquats
Request fulfilled  

---------------
Store inventory
---------------
Apples: 43, Oranges: 26, Pineapples: 0, Persimmons: 43, Kumquats: 22
---------------  

Customer 0 requests, 4 Apples, 0 Oranges, 2 Pineapples, 1 Persimmon, 3 Kumquats
Customer 0 waiting . . .  

Customer 1 requests, 2 Apples, 9 Oranges, 5 Pineapples, 7 Persimmons, 3 Kumquats
Customer 1 waiting . . .  

Customer 2 requests, 2 Apples, 9 Oranges, 5 Pineapples, 7 Persimmons, 3 Kumquats
Customer 2 waiting . . .  

Customer 3 requests, 2 Apples, 9 Oranges, 5 Pineapples, 7 Persimmons, 3 Kumquats
Customer 3 waiting . . .  

** RESTOCKING **  

---------------
Store inventory
---------------
Apples: 50, Oranges: 50, Pineapples: 50, Persimmons: 50, Kumquats: 50
---------------
Customer 0 requests, 4 Apples, 0 Oranges, 2 Pineapples, 1 Persimmon, 3 Kumquats
Request fulfilled
. . .


Answer:


7.

If you make sure that an object with synchronized methods calls notifyAll() to match every wait() method, are you guaranteed not to experience deadlock? Explain.


Answer:


8.

Explain the difference between the notify() and notifyAll() methods. Will using one over the other guarantee you will not experience deadlock?


Answer:


9.

A Store object has two methods,

     synchronized void restock()
     synchronized boolean processOrder(Order request)

A Customer thread calls the processOrder() method with its order. If the order cannot be fulfilled because there is not enough inventory (the method returns false), the Customer thread calls wait().

At certain time intervals a store manager restocks the inventory using the following segment of code:

        try
        {
           if (myStore.timeToRestock())
           {
              myStore.restock();
              notifyAll();
           }
           sleep(10);
        }
       catch (InterruptedException e) { }

In this example, why won't the call to notifyAll() wake up any waiting threads?


Answer: