Java Reference
In-Depth Information
try
{
serverSocket = new ServerSocket(PORT);
}
catch (IOException e)
{
System.out.println("\nUnable to set up port!");
System.exit(1);
}
//Create a
Resource
object with
//a starting resource level of 1…
Resource item = new Resource(1);
//Create a
Producer
thread, passing a reference
//to the
Resource
object as an argument to the
//thread constructor…
Producer producer = new Producer(item);
//Start the
Producer
thread running…
producer.start();
do
{
//Wait for a client to make connection…
Socket client = serverSocket.accept();
System.out.println("\nNew client accepted.\n");
//Create a
ClientThread
thread to handle all
//subsequent dialogue with the client, passing
//references to both the client's socket and
//the
Resource
object…
ClientThread handler =
new ClientThread(client,item);
//Start the
ClientThread
thread running…
handler.start();
}while (true); //Server will run indefi nitely.
}
}
Method
addOne
of
Resource
will be called by a
Producer
object and will
attempt to add one item to the resource level. Method
takeOne
of
Resource
will be
called by a
ConsumerClient
object and will attempt to remove/consume one item.
Both of these methods will return the new resource level. Since each of these meth-
ods will modify the resource level, they must both be declared with the keyword
synchronized
.
The code for the
Producer
class is shown below. As in previous examples, a
randomising feature has been included. This causes the producer to wait 0-5 s
Search WWH ::
Custom Search