Threads

HY556 – Distributed Systems Computer Science Department University of Crete

Java threads
There are 2 ways in Java to create a Thread Create a class that extends the Thread class Create a class that implements the Runnable interface Either way, the programmer must create a class that implements the public void run() method When the start() method is called (no need to be defined by the programmer –it is defined in the Thread class), the thread goes to Runnable state, and its run() method is invoked.

HY556 - Distributed Systems

2

Java threads: extending Thread
To create a new thread, create a class that extends the Thread class and implements the public void run() method When the start() method is called in that class (which is defined in the superclass Thread), the run() method is invoked from the virtual machine and starts running.

HY556 - Distributed Systems

3

Java threads: extending Thread
Example: class MyThread extends Thread{ public MyThread(){ /* do some initializations */ } public void run(){ /* do whatever we want to do in separate flow of control */ } } public class MyThreadTester{ public static void main(String[] args){ Thread foo = new MyThread(); foo.start(); } }
HY556 - Distributed Systems 4

Java threads: implementing Runnable
Runnable is an interface. To implement it, implement the public void run() method To create a new thread, create a class implementing the Runnable interface and pass an instance of it as argument to a Thread object Useful in the case where our class already extends another class, because in Java a class cannot extend two classes simultaneously but it can implement numerous interfaces.

HY556 - Distributed Systems

5

Java threads: implementing Runnable
Example: class MyThread implements Runnable{ public MyThread(){ /* do some initializations */ } public void run(){ /* do whatever we want to do in separate flow of control */ } } public class MyThreadTester{ public void main(String[] args){ Thread foo = new Thread(new MyThread); foo.start(); } }
HY556 - Distributed Systems 6

Putting it all together: a multithreaded server
class ConnectionHandler extends Thread{ private Socket s; public ConnectionHandler(Socket s){ this.s = s; start(); } public void run(){ try{ InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream(); /* handle the socket as explained previously */ … }catch(IOException ex){ ex.printStackTrace(); } } } HY556 - Distributed Systems 7

Putting it all together: a multithreaded server
public class MultiThreadedServer { public static final int PORT = 12345; public static void main(String args[]) throws Exception{ ServerSocket ss = new ServerSocket(PORT); while (true){ try{ new ConnectionHandler( ss.accept() ); }catch(IOException ex){ ex.printStackTrace(); } } } }
HY556 - Distributed Systems 8

References
http://java.sun.com/j2se/1.3/docs/api http://java.sun.com/docs/books/tutorial

HY556 - Distributed Systems

9

Sign up to vote on this title
UsefulNot useful