Sunteți pe pagina 1din 3

Copyright 2003 by Barry B.

Brey

Multithreading in Java
A thread is nothing more than a class in Java. The difference is that a thread class is started using the .start() member function instead of a mere call to a member of the class. For example, Figure 1 shows two classes. One is used to start a thread class. The thread must extend Thread and you must use the run() member function of the thread class to start the thread and its software. Note that we normally place the thread and the caller in different files. A thread is a function or a class that is scheduled by the operating system and can run with other threads. The advantage of threads is really not apparent except that it allows the user to perform tasks in parallel. When computers come with more than one processor (as in the new HyperThreaded architecture in future Pentiums) threads will run in parallel in different microprocessors. This will speed up software execution.
Figure 1 public class Test { new Thread1().start(); } public class Thread1 extends Thread { public Thread1() { super("Thread1"); } public void run() { //thread software placed here! } }

The scheduler (as you might recall from operating systems) is called on each system clock tick (once a millisecond for example). The scheduler then starts a new thread every millisecond. If multiple microprocessors are present the scheduler can start a new thread in each of the microprocessors so that they execute in parallel. Without multiple microprocessors the illusion of parallel execution occurs because the threads are executed for a millisecond before being suspended for a later time slice. An example might include 2 threads which would gain processor time every other millisecond. To a human both threads would appear to execute concurrently. A multithreaded server could be implemented as in Figure 2. This server will start a new worker thread every time that it connects to 2 internet client. The worker thread then proceeds to communicate with the client pair as if they are the only clients connected to the socket. The server then starts looking for another client pair and, if found, starts yet a second worker thread and so forth. Each pair of clients is handled by a different worker thread.
Figure 2 import java.net.*; import java.io.*; public class MultiServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; Socket socket1 = null;

Socket socket2 = null; boolean listening = true; // create the one and only server socket at port 4200 try { serverSocket = new ServerSocket(4200); } catch (IOException e) { System.err.println("Could not listen on port: 4200."); System.exit(-1); } // get client pairs and start a new thread when the pair connects while (listening) { socket1 = serverSocket.accept(); PrintWriter out1 = new PrintWriter(socket1.getOutputStream(), true); BufferedReader in1 = new BufferedReader(new InputStreamReader( socket1.getInpu tStream())); out1.println("X"); socket2 = serverSocket.accept(); PrintWriter out2 = new PrintWriter(socket2.getOutputStream(), true); BufferedReader in2 = new BufferedReader(new InputStreamReader( socket2.getInputStream())); out2.println("O"); new MultiServerThread(socket1, socket2).start(); } serverSocket.close(); socket1.close(); socket2.close(); } }

If you examine Figure 2 you will notice that MultiServerThread is started only after 2 connections to the socket at port 4200 occur. The first connection is returned the letter X by the server and the second connection is returned the letter O. This means that when the clients connect the first client receives the letter X and the second of the pair receives the letter O. Once both clients in the pair are connected then a new MultiServerThread is stared and passed the socket addresses for both clients so it can handle the client pair. You might think of the X or the O as an identification signal back to the client. Figure 3 illustrates the shell of the server thread that handles a pair of clients. Communications to the X client are through in1 and out1 and communications to client O are through in2 and out2.
Figure 3 import java.net.*; import java.io.*; public class MultiServerThread extends Thread { private Socket socket1 = null; private Socket socket2 = null; public MultiServerThread(Socket socket1, Socket socket2) { super("MultiServerThread"); this.socket1 = socket1; this.socket2 = socket2; } public void run() { try { PrintWriter out1 = new PrintWriter(socket1.getOutputStream(), true);

BufferedReader in1 = new BufferedReader(new InputStreamReader( socket1.getInputStream())); PrintWriter out2 = new PrintWriter(socket2.getOutputStream(), true); BufferedReader in2 = new BufferedReader(new InputStreamReader( socket2.getInputStream())); out1.println("Started"); // inform client X started out2.println("Started"); // inform client O started while (true) {

//simple chat server between two clients if ( in1.ready() ) { String string1 = in1.readLine(); out2.println(string1); if ( string1.equalsIgnoreCase(logout); break; } else if ( in2.ready() ) { String string2 = in2.readLine(); out1.println(string2); if ( string2.equalsIgnoreCase(logout); break; )

} out1.close(); in1.close(); out2.close(); in1.close(); socket1.close(); socket2.close(); } catch (IOException e) { e.printStackTrace(); } } }

Figure 3 sets the frame for the server and its use depends on the information that needs to pass from one client to the other. For a simple chat client (between pairs of users) you could simply read from client 1 {String string1 = in1.readLine()} and send to client 2 {out2.println(string1))} and read from client 2 {String string2 = in2.readLine()} and send to client 1 {out1.println(string2))}. In this example if someone type logout the client pair disconnects and the thread is retired. To make the chat server work more efficiently we have used in1.ready() or in2.ready() to check and see if data is being sent by a client. The ready() memory returns true if data are ready to be read from a client and false if no data is ready. This should be enough to get you started with threaded servers and threads in general. Again this example shows pairs of clients that are acted upon and can be modified for one client or as many as you need before staring the thread.

S-ar putea să vă placă și