CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Threads

Threads
Application
OrderTaker class

The code for the OrderTaker class

public class OrderTaker extends Thread
{
    private static int orderNumber = 1;

    private int count = 0;
    private int maxOrders;
    private OrderQueue orderQueue;
    private String name;

    public OrderTaker(int orderCount, OrderQueue orderQueue)
    {
        this.maxOrders = orderCount;         // number of orders to create
        this.orderQueue = orderQueue;        // order queue
    }

    public void run()
    {
        int orderNumber;
        Order order;
        while (count < maxOrders)
        {
            order = new Order(getOrderNumber());
            orderQueue.pushOrder(order);     // add order to the queue
            System.out.println(order.toString() + " created by "
                + this.getName());
            count++;
            try
            {
                Thread.sleep(1000);          // delay one second
            }
            catch (InterruptedException e)
            {}                               // ignore interruptions
        }
    }

    private synchronized int getOrderNumber()
    {
        return orderNumber++;
    }

}
Previous | Order Queue application | Classes | OrderQueueApp class | Order class | OrderTaker class | Orderhhandler class | OrderQueue class