CS451 Lecture 7: Multiple Threads in Java - PowerPoint PPT Presentation

1 / 17
About This Presentation
Title:

CS451 Lecture 7: Multiple Threads in Java

Description:

Tasks may be multitasked by a machine to appear to be running simultaneously or ... catch (IOException e) { }} 16. CS451 - Lecture 7. ClassServer application ... – PowerPoint PPT presentation

Number of Views:29
Avg rating:3.0/5.0
Slides: 18
Provided by: frankm8
Category:

less

Transcript and Presenter's Notes

Title: CS451 Lecture 7: Multiple Threads in Java


1
CS451Lecture 7 Multiple Threads in Java
  • Yugi Lee
  • STB 555
  • (816) 235-5932
  • yugi_at_cstp.umkc.edu
  • www.cstp.umkc.edu/yugi
  • Acknowledgement This lecture is based on
    material courtesy of Monash University

2
Contents
  • Threads
  • Extending the Thread class
  • Implementing the Runnable interface
  • Threading a network server
  • Problems with a threaded server.

3
Threads
  • Tasks may be multitasked by a machine to appear
    to be running simultaneously or may actually be
    running on different processors at the same time.
  • In C or C making a system call to the
    operating system which creates a new process,
    allocate processor time to each process running
    on the machine switching between them.
  • In Java creating multiple threads.
  • Threads are like the processes, but are
    light-weight, not much overhead and operating
    system resources, largely managed by the virtual
    machine.
  • As everything belongs to a class, threading is
    integrated into objects. New threads are created
    when objects are started in their own thread.

4
Extending the Thread class
  • must provide a run() method.
  • The objects can be constructed, but a new thread
    of execution is not created until the object has
    its inherited method start() called. This in turn
    starts a new thread and calls the object's run
    method run().
  • Thread.sleep() is a static method which puts the
    program to sleep for a period.

5
Extending the Thread class
  • Thread is not associated with any particular
    object, though owned by the particular object
    which started it,
  • moving on from there to execute methods in other
    objects
  • Methods of other objects can be called within run
    and then these can call methods in other objects
    and so on.

6
Extending the Thread class
  • class ThreadTest extends Thread
  • private int id 0
  • public ThreadTest(int id)
  • this.id id
  • public void run()
  • System.out.println("Thread " id "
    started")
  • try
  • Thread.sleep((long)(Math.random() 1000))
  • catch (InterruptedException e)
  • System.out.println("Thread " id "
    finishing")

7
Extending the Thread class
  • public class ThreadDemo
  • public static void main(String args)
  • ThreadTest tt new ThreadTest1
  • System.out.println("Main creating Thread 1")
  • tt0 new ThreadTest(1)
  • System.out.println("Main creating Thread 2")
  • tt1 new ThreadTest(2)
  • System.out.println("Main finished creating
    threads")
  • System.out.println("Main starting Thread 1")
  • tt0.start()
  • System.out.println("Main starting Thread 2")
  • tt1.start()
  • System.out.println("Main finished starting
    threads")

8
Implementing the Runnable interface
  • Since implementing an interface does not add any
    functionality, to add threading abilities to a
    Runnable class, it must be encapsulated within an
    object of type Thread.
  • passing the Runnable object as an argument to a
    Thread class constructor which then returns a
    Thread object containing the Runnable object.
  • Invoking the Thread object's start() method
    creates the new thread and in turn, invokes the
    run() method of the contained Runnable object.

9
Implementing the Runnable interface
  • class ThreadTest2 implements Runnable
  • private int id 0
  • public ThreadTest2(int id)
  • this.id id
  • public void run()
  • System.out.println("Thread " id "
    started")
  • try
  • Thread.sleep((long)(Math.random() 1000))
  • catch (InterruptedException e)
  • System.out.println("Thread " id "
    finishing")

10
Implementing the Runnable interface
  • public class RunnableDemo
  • public static void main(String args)
  • ThreadTest2 tt new ThreadTest22
  • System.out.println("Main creating Thread
    1")
  • tt0 new ThreadTest2(1)
  • System.out.println("Main creating Thread
    2")
  • tt1 new ThreadTest2(2)
  • System.out.println("Main finished creating
    threads")
  • System.out.println("Main starting Thread
    1")
  • new Thread(tt0).start()
  • System.out.println("Main starting Thread
    2")
  • new Thread(tt1).start()
  • System.out.println("Main finished starting
    threads")

11
Threading a Server
  • Without threads The ClassServer application
    allows on one client connection at a time. Other
    clients must wait until the current client has
    completed.
  • Using threads the server can serve multiple
    clients at once.
  • The server accepts a connection from a client
  • then creates a new thread to deal with that
    connection allowing it to return almost
    immediately to accept other connections.

12
ClassSever Multiple Connection
  • public ClassServerMulti(String dataFile)
  • fillVectors(dataFile)
  • try
  • ServerSocket classSocket new
    ServerSocket(11000)
  • while (true)
  • Socket clientSocket classSocket.accept()
  • new ClassRequestBroker(clientSocket, guys,

  • girls,unsure).start()
  • catch (Exception e)

13
ClassSever Multiple Connection
  • public ClassRequestBroker(Socket clientSocket,
    Vector guyList, Vector girlList, Vector
    unknownList)
  • guys guyList
  • girls girlList
  • unsure unknownList
  • requestor clientSocket
  • public void run()
  • try
  • BufferedReader br
  • new BufferedReader(new InputStreamReader(
  • requestor.getInputStream()))
  • PrintWriter ps
  • new PrintWriter(requestor.getOutputStream())

14
ClassSever Multiple Connection
  • ps.println("Welcome to the Java class info
    server.")
  • ps.println("Type \"all\" for a list of all
    students,")
  • ps.println("type \"guys\" for a list of all male
    students,")
  • ps.println("type \"girls\" for a list of all
    female students.")
  • String request ""
  • boolean connected true
  • while (connected)
  • request br.readLine()
  • if (request.toUpperCase().equals("QUIT"))
  • connected false

15
ClassSever Multiple Connection
  • else
  • if (request.toUpperCase().equals("GUYS"))
  • listMaleStudents(ps)
  • else if (request.toUpperCase().equals("GIRLS"))
  • listFemaleStudents(ps)
  • else if (request.toUpperCase().equals("ALL"))
  • listMaleStudents(ps)
  • listFemaleStudents(ps)
  • else
  • ps.println("\"" request "\" not
    understood")
  • br.close()
  • ps.close()
  • requestor.close()
  • catch (IOException e)

16
ClassServer application
  • The constructor for ClassServerMulti now contains
    an infinite loop which is acceptable as it blocks
    while waiting for client connections, therefore
    it is not a busy loop .
  • All the methods containing the code for
    communicating with the client are now
    encapsulated in a ClassRequestBroker object,
    which extends the Thread class
  • As with all threads, the body of the controlling
    code for ClassRequestBroker is contained within
    its run method
  • After the accept method in ClassServerMulti has
    completed (i.e., a new client has connected to
    the server), a new instance of the
    ClassRequestBroker class is created and its run
    method invoked - thereby beginning the
    communication process with the new client

17
Problems with Threading a Server
  • the number of threads may prove to much of a
    burden to the server machine (if clients stay
    connected for a lengthy period of time.)
  • Protocols such as the HTTP protocol
  • help minimize this by only connecting for a
    short period then closing the connection.
  • may reduce the number of threads running on the
    server at any one time
  • uses more resources and bandwidth in
    connecting/disconnecting from the server each
    time.
  • difficult for web-developers to keep track of
    the data exchanged with individual clients across
    disconnections and reconnections.
Write a Comment
User Comments (0)
About PowerShow.com