3 Replies - 7969 Views - Last Post: 08 February 2010 - 01:58 PM Rate Topic: -----

#1 ashnar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 28-December 09

Multithreaded Client/Server Application where multiple threads acts as

Posted 29 December 2009 - 05:45 PM

Hi! If I am lucky somebody will find time to look at my code and explain to me a one issue that does not allow me to complete the task. Or maybe, I just will find that I should start from the scratch because my approach is wrong from the beginning. Any suggestions welcomed, I am beginner so anything what might seem unimportant for you may be a milestone for me. Now let me introduce the task;

A takeaway restaurant has a number of cashiers who take orders from customers. The orders are added to a list of pending orders. There are several cooks working in the kitchen who each take the next order from the list, cook it and deliver it, and then go back to get another order to cook.

Model this using Java threads, with classes Cashier, Cook and OrderList to represent the elements of the simulation. A Cashier has a name and adds an order to the OrderList at random intervals (a random delay between orders of up to 5 seconds). The order information includes the Cashier’s name, the current time, and an order number (where each order taken by anyone gets the next available order number). A Cook also has a name. Each Cook removes an order from the OrderList when one is available, takes a random amount of time to cook it (a random delay of up to 7 seconds) and then delivers it, which you can simulate by printing out the name of the Cook and the information from the order. Make sure everything is synchronized so that orders don’t get lost and the ‘delivery’ details do not get jumbled together when they are displayed.


To solve this I developed following code; (This all works fine so you may skip this code and move on to real problem, I will post it in case that you would like to clarify my further approach or task requirements)
package orderingSystem;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class Cashier implements Runnable 
{
	public Cashier(OrderList passOrderList) 
	{
		orderList=passOrderList;
	}
	
	private static final int MAX_DELAY = 5000;
	OrderList orderList;
	
	int orderNumber = 0;	
	public String order, strorderNumber;

	public void run()
	{
		while(true)
		{	
			try {
				
				Date now = new Date();
				Format fTime = new SimpleDateFormat("hh:mm:ss a");
				order = ("Order made by " + Thread.currentThread().getName()+ " at " + fTime.format(now)+ "\n");
			synchronized (this){
				orderList.addOrder(order);
				}
				Random randomNumber = new Random();
				Thread.sleep(randomNumber.nextInt(MAX_DELAY));
				} catch (InterruptedException exception){
			}
		}
	}

}
package orderingSystem;

import java.util.Random;

public class Cook implements Runnable 
{
	public Cook(OrderList passOrderList) 
	{
		orderList=passOrderList;
	}
		
		private static final int PREPARATION_TIME = 7000;
		OrderList orderList;
		
		int orderNumber = 0;	
		public String preparingOrder;

		public void run()
		{
			while(true)
			{	
				try {
					Random randomNumber = new Random();
					Thread.sleep(randomNumber.nextInt(PREPARATION_TIME));
				synchronized (this){
					orderList.prepareOrder(Thread.currentThread().getName());
				}
					} catch (InterruptedException exception){
				}
			}
		}

}

package orderingSystem;

import java.util.Random;

public class Cook implements Runnable 
{
	public Cook(OrderList passOrderList) 
	{
		orderList=passOrderList;
	}
		
		private static final int PREPARATION_TIME = 7000;
		OrderList orderList;
		
		int orderNumber = 0;	
		public String preparingOrder;

		public void run()
		{
			while(true)
			{	
				try {
					Random randomNumber = new Random();
					Thread.sleep(randomNumber.nextInt(PREPARATION_TIME));
				synchronized (this){
					orderList.prepareOrder(Thread.currentThread().getName());
				}
					} catch (InterruptedException exception){
				}
			}
		}
}


My next task is to write this as a distributed system and allow elements to communicate over the network. I chosen to solve this problem with use of sockets and java.net.

At this stage my distributed version include only a cashier and order list communication. I will work on a cook if I manage to get this two working. At the moment my code is able to create orders and pass them over ServerLittleHelper class to the OrderList. The problem is that as soon as cashier thread sends order to orderList the thread stops its execution. So, instead of having a cashier thread that adds orders in 5sec intervals the threads stops execution after the first order is sent. I cannot understand why cashier threads are stopped and I could not find the reason for this behaviour. It would be helpful if somebody could point out where the problem lies, and explain why the cashier threads dies for its own.

Please help me as I have no more patience to look at them dying. :)


Below the working code for problematic part.

import java.util.ArrayList;

public class OrderList {
	
	ArrayList<String> arrOrderList = new ArrayList<String>(); 
	int orderUniqueNumber = 1;
	
	static String[] cashierName = { "George", "Lucky", "Elmo", "Style", "Yan"};
	private static final int NUMBEROFCASHIERS = 2;

	
	public static void main(String args[]) throws Exception
	{
		// Create the OrderList
		OrderList arrOrderList = new OrderList();
		
		// Creates cashier threads that are supposed to add orders to OrderList
		
		for (int i = 0; i<NUMBEROFCASHIERS; i++){
			Cashier newCashier = new Cashier(arrOrderList);
			Thread cashierThread = new Thread(newCashier);
			cashierThread.setName(cashierName[i]);
			cashierThread.start();
		}

		// Creates Server
		new SystemServer(arrOrderList);
	}
	
	public void addOrder(String order){
		
		String strOrderUniqueNumber = Integer.toString(orderUniqueNumber);
		arrOrderList.add("Order No: " +strOrderUniqueNumber+" " + order);
		orderUniqueNumber++;
		System.out.println("Pending Orders: " + "\n" + arrOrderList + "\n");
		
	}
}


import java.io.*;
import java.net.*;

public class SystemServer {

   ServerSocket orderListServer;
   OrderList orderList;

   ServerSocket server = null;
   Socket client  = null;
   BufferedReader incomingOrder = null;
   PrintWriter out = null;
   String line;

   public SystemServer(OrderList orderList) throws Exception {
		
		 this.orderList = orderList;
		 runServer();
   } 

   public void runServer() {
	
	   try{
			server = new ServerSocket(4444);
	  } catch (IOException e) {
			System.out.println("Could not listen on port 4444");
			System.exit(-1);
	  }
	
	  while(true){
			ServerLittleHelper slh;
			try{
				  slh = new ServerLittleHelper(server.accept(), line, orderList);
				  Thread t = new Thread(slh);
				  t.start();
			} catch (IOException e) {
				  System.out.println("Accept failed: 4444");
				  System.exit(-1);
			  }
	  }
   }
}


import java.io.*;
import java.net.*;

class ServerLittleHelper implements Runnable {
  
	private Socket client;
	  private String order;
	  OrderList orderList;
  
	  ServerLittleHelper(Socket client, String order, OrderList orderList ) {
		  this.client = client;
		  this.order = order;
		  this.orderList = orderList;
	  }

	  public void run(){
		  String line;
		  BufferedReader in = null;
		  PrintWriter out = null;
		  
		  try{
			  in = new BufferedReader(new InputStreamReader(client.getInputStream()));
			  out = new PrintWriter(client.getOutputStream(), true);
		  } catch (IOException e) {
				  System.out.println("Little Helper: IO Error");
				  System.exit(-1);
		  }

	while(true){
	  try{
		 line = in.readLine();
		 order = line;

		 out.println(line);
		 orderList.addOrder(order);
	   } catch (IOException e) {
		 System.out.println("Read failed");
		 System.exit(-1);
	   }
	}
  }
}

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;

public class Cashier implements Runnable
{
	public Cashier(OrderList passOrderList) 
	{
		orderList=passOrderList;
	}
	
		private static final int MAX_DELAY = 5000;
		OrderList orderList;
		Socket socket;
		PrintWriter out = null;
		BufferedReader in = null;
	
	
		int orderNumber = 0;	
		public String order, strorderNumber;

	public void run()
	{
			try{
									
				socket = new Socket("127.0.0.1", 4444);
				out = new PrintWriter(socket.getOutputStream(), true);
		 		in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				
				
		 		//Creates pseudo "order" as a String object that has to be passed to the OrderList
		 		Date now = new Date();
				Format fTime = new SimpleDateFormat("hh:mm:ss a");
				order = ("Order made by " + Thread.currentThread().getName()+ " at " + fTime.format(now)+ "\n");
				
				synchronized (this){
				out.println(order);
				}
						
				Random randomNumber = new Random();
				Thread.sleep(randomNumber.nextInt(MAX_DELAY));
				} catch (InterruptedException exception){		
		
				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	}
}




Or maybe should I take different approach and run and create cashiers separately from OrderList? Even if, it still would be good to know why cashier thread dies in example above.

Is This A Good Question/Topic? 0
  • +

Replies To: Multithreaded Client/Server Application where multiple threads acts as

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8325
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Multithreaded Client/Server Application where multiple threads acts as

Posted 29 December 2009 - 10:04 PM

Ouf... can you narrow down your problem ?
remove code that is not relevant to your problem and post only the few lines of code that do not seem to work
and may be that doing this exercide you'll find the problem by yourself :)
Was This Post Helpful? 1
  • +
  • -

#3 ashnar  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 28-December 09

Re: Multithreaded Client/Server Application where multiple threads acts as

Posted 30 December 2009 - 10:00 AM

Problem Solved :).

I needed to put cashier thread in the loop to keep it executing.
Didn't know that run() must be in a loop. :)

Thanks for attempt! :^:
Was This Post Helpful? 0
  • +
  • -

#4 skyhigh8  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 07-February 10

Re: Multithreaded Client/Server Application where multiple threads acts as

Posted 08 February 2010 - 01:58 PM

hey ashnar,

I noticed you're doing the same thing as me and I was wondering if you've done the third part where you've got to send messages from the cook to the cashier as I can't figure out how to implement it after several attempts.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1