jueves, 29 de abril de 2010

Java Process and Threads. TCP Java Server.

This post try it to explain how to manage Process, Threads and concurrence.

The main goal is explain how is a thread, and how is a process.
We can explain very well this topics with follow ilustration of Tanenbaum book :

The ilustration show in a) case three process with one thread into each one, in case b) we can see ONE process with three threads into the unique process.
The main diference between Process and Thread is that the thread is more ligth than a Process in order of the Threads works in the details of thw Process`s work and it can share the Thread stack with the others Threads.

A very good example of Process and Threads can be a Server and a Client.The server will be a Process wich accepts requests of a clients. Whe it accept one request, will create a Thread to give service to a client request.
We need three JavaClass: Server.java, Process.java and Cliente.java.

Server class create a s = new ServerSocket(9000); and wait to accept conecctions. When a conecction from a Cliente is coming, the server instance one Process with Procesador proc = new Procesador(cont,s.accept()); proc.start();

In this moment, Server is waiting for a new incoming conecction, and his Thread Process is working with the cliente conecction. The Processador read, operate and request the conecction cliente: b = new BufferedReader( new InputStreamReader ( sc.getInputStream() ) ); , p = new PrintStream ( sc.getOutputStream() );

Now, only need the Cliente operations: it´s simple, only create a socket s = new Socket(host,port); and write the request to a server.
We can see the result.

One iteration between Server and two clients:

One cliente close the conecction, but the oher cliente is coneccted and work in the server.

The client #3 executed two operations in the server and close conecction. Really close the Process Thread.

No hay comentarios: