Threads in Java - PowerPoint PPT Presentation

1 / 23
About This Presentation
Title:

Threads in Java

Description:

Threaded programs create two or more simultaneous flows of control to accomplish ... telnet, then issue an open command using localhost or 127.01.01.01 and port 4000 ... – PowerPoint PPT presentation

Number of Views:97
Avg rating:3.0/5.0
Slides: 24
Provided by: mer3
Category:

less

Transcript and Presenter's Notes

Title: Threads in Java


1
Threads in Java
  • Rick Mercer

2
2 tasks at the "same time"
  • Threaded programs create two or more simultaneous
    flows of control to accomplish multiple tasks at
    the same time
  • Thread sequential flow of control within a
    program
  • Single threaded programs have 1 path
  • Multi-threaded programs have 2 or more paths

3
From the Java Tutorial Discussion of Threads
4
Why use threads?
  • Sometimes it makes sense to use multiple threads
    in a program to accomplish multiple simultaneous
    tasks
  • Use threads when you dont want to wait for a
    particular process to finish
  • This allows other things to continue such as
  • Continuing a program before images are created
  • Reading a web page as a large file downloads
  • Running a server while a separate thread
    "listens" for new connections
  • 335 Fall 05, try Sample code that follows

5
Keep a list of clients
  • import java.net.ServerSocket
  • import java.net.Socket
  • import java.util.ArrayList
  • public class RecognizeClientConnections
  • public static void main(String args)
  • new RecognizeClientConnections()
  • // A list of clients to talk to that are added
  • // anytime this server is running
  • private ArrayList listOfClients
  • // A private inner class running in a separate
    thread to
  • // accept many connections, which may be days
    later
  • private ClientResponder clientResponder

6
Start a server in a new thread
  • public RecognizeClientConnections()
  • // Part of the model
  • listOfClients new ArrayList()
  • // Start a new Server socket (see next
    slide)clientResponder new ClientResponder(4000)
  • // Start a separate thread to listen for clients
  • // This start message will call the run method
    below
  • clientResponder.start() // Call run method
    below

7
Constructor started server
  • private class ClientResponder extends Thread
  • private ServerSocket server
  • public ClientResponder(int port)
  • try
  • server new ServerSocket(port)
  • catch (Exception e)
  • throw new RuntimeException("Could not
    start")

8
Infinite loop in a Different Thread
  • public void run()
  • while (true)
  • try
  • // print list of clients each time a new
    client
  • // telnets into this this server
  • Socket client server.accept()
  • listOfClients.add(client)
  • System.out.println("Clients "
    listOfClients)
  • catch (Exception e)
  • throw new RuntimeException("Server died")

9
Many clients in ArrayList
  • Output after opening
  • Two Command Prompt windows on the local machine,
    using telnet to connect
  • Open a Command Prompt on a different machine in
    the lab
  • Program now has 3 different clients
  • Clients /127.0.0.14882
  • Clients /127.0.0.14882, /127.0.0.14883
  • Clients /127.0.0.14882, /127.0.0.14883,
    /150.135.1.1104289

10
The clients
  • First start the server (run the previous code)
  • Start up telnet from the same machine
  • from the command line, enter telnet, then issue
    an open command using localhost or 127.01.01.01
    and port 4000

11
Second client recognized
  • The server output is
  • Clients /127.1.1.14888
  • Start telnet from Command Prompt on different
    machine
  • Output
  • Clients /127.1.1.14888, /150.12.69.744889

12
Thread Stalling
  • What happens when a method needs to wait for
    something before returning, such as user
    connecting from the network?
  • Recall accept()
  • Use threads when you need to handle other tasks
    while waiting to accept new network connections
  • especially when there may be many and they may be
    days, or weeks from now

13
Back to the reasons
  • The previous slides should allow you to have a
    separate thread that simply prints the client's
    toString() each time a new client opens a
    connection

14
Multithreading
  • We can accept connections in a different thread
  • Java allows us to create new threads for handling
    concurrent tasks
  • Each thread gets its turn to get its job done

15
How?
  • Java provides two ways to create a new thread.
  • We will use this one"
  • Extend the Thread class(java.lang.Thread)

16
Javas Thread Class
  • When creating a new thread by extending the
    Thread class, override the run() method
  • run does nothing, so you need to make it do the
    right things
  • public class AnotherThread extends Thread
    public AnotherThread() // Initialize
    parameters public void run() // do
    something

17
Now What?
  • To start a new thread, use the inherited method
    start()
  • AnotherThread at new AnotherThread()at.start
    ()

18
What happens in start()?
  • start() is responsible for two things
  • Instructing the JVM to create a new thread
  • Call your Thread objects run method in the new
    thread
  • You might think of run as being similar to main
  • main is called by the JVM

19
More about Thread.run()
  • Like main, the run method defines a starting
    point for the JVM
  • What happens when the run method exits?
  • The thread ends

20
Multithreading Pros and Cons
  • Pro Multiple threads run concurrently on the
    system
  • Multiple tasks can be handled at once
  • Processing can be done in the background so as
    not to interrupt the user
  • Con Multiple threads run concurrently on the
    system
  • No more guarantees as to what has already
    happened, what objects have been initialized yet,
    etc
  • Code now has to be thread-safe or
    synchronized
  • Debugging becomes much harder

21
Tips for Writing Thread-safe Code
  • Limit a threads access to common variables
  • Track changes to instance variables through
    get/set methods
  • When two or more threads are accessing a
    collection, make sure the collection being used
    is synchronized (i.e. using Vector instead of
    ArrayList

22
How do I stop it?
  • Methods used to directly stop or suspend threads
    have been depreciated in the Java API, as they
    could cause synchronization issues.
  • The threads run() method must finish and return
    for the thread to stop

23
Interesting Facts
  • In many of your Swing programs, main has
    consisted of creating a new JFrame
  • This starts a new thread that the GUI runs in and
    returns immediately main then finishes
  • Why doesnt the program end when main does?
  • Java applications only exit when all of their
    threads have stopped
Write a Comment
User Comments (0)
About PowerShow.com