Multithreading: basic concepts - PowerPoint PPT Presentation

1 / 22
About This Presentation
Title:

Multithreading: basic concepts

Description:

A thread is a single sequential flow of control within a program. Similar to the sequential programs: a single thread has a beginning, an end, a ... Deprecated now. ... – PowerPoint PPT presentation

Number of Views:124
Avg rating:3.0/5.0
Slides: 23
Provided by: patric190
Category:

less

Transcript and Presenter's Notes

Title: Multithreading: basic concepts


1
Multithreading basic concepts
2
What is a thread?
  • Definition
  • A thread is a single sequential flow of control
    within a program.
  • Similar to the sequential programs a single
    thread has a beginning, an end, a sequence, and
    at any given time during the runtime of the
    thread there is a single point of execution.
  • However, a thread itself is not a program. It
    cannot run on its own, but runs within a program.
  • Key issues
  • Not about a single sequential thread, but rather
    about the use of multiple threads in a single
    program all running at the same time and
    performing different tasks.

3
The Benefits of Multithreading
  • Improving application responsiveness
  • Imagining that you need to deal with a lengthy
    operation as a result of an event.
  • Improving program structure
  • Suppose you were asked to implement multitasks
    within a non-threaded program, you may need to
    devote much of your code just to coordinating the
    tasks.
  • Using fewer system resources
  • Comparing with multi-processes, implementing
    multi-threads in the same process is much much
    easier and less expensive
  • Using multiprocessors efficiently
  • A multithreaded application performance can
    scales appropriately when multicore processors
    and multithreaded processors are available

4
Examples
class ThreadExamples public static void
main(String args) JFrame frame frame
new JFrame() frame.setTitle("Swing!") frame.
setSize(320, 256) frame.setVisible(true) Sys
tem.out.println("In the middle") System.out.pri
ntln("Finishing")
5
Creating Your Own Threads(1)
  • In Java, the class Thread is used to create and
    control threads.
  • To create a thread, a new instance of this class
    must be created.
  • However, the thread does not start running right
    away. Thread.start() must be called to actually
    make the thread run.
  • The definition of each thread's behavior is
    contained in its run() method.
  • A run method is equivalent to main() in a
    traditional program a thread will continue
    running until run() returns, at which point the
    thread dies.
  • There are two ways to create a thread
  • Extending the Thread class.
  • Implement the Runnable interface

6
Creating Your Own Threads (2)
  • Subclass a Thread with the code for the thread in
    the run method
  • The Thread class itself implements Runnable
    interface, though its run method does nothing.
  • An application can subclass Thread, providing its
    own implementation of run()
  • Statements within the run()method constitute the
    portion of the program that runs as the thread.
  • public class Thread extends Object implements
    Runnable
  • Although it is the run method code that executes,
    a thread is actually started via the start method

7
Creating Your Own Threads (3)
  • Steps
  • Create object by extending the Thread class and
    overriding the run() method
  • Create an instance of it (name optional)
  • Thread f new Foo(fred)
  • Send the message start to the object
  • f.start( )

class Foo extends Thread public void run()
// ... stuff to do ...
8
Creating Your Own Threads (4)
  • Build a Runnable with the code for the thread in
    the run method
  • The Runnable interface should be implemented by
    any class whose instances are intended to be
    executed by a thread.
  • Only one method public void run()
  • The content of the run() method is the portion of
    your program that will become the new thread.
  • It must be a public method, and it doesnt
    require an argument list or have a return value.

9
Creating Your Own Threads (5)
  • Steps
  • Create object by implementing Runnable interface
  • Create a Thread object passing in the
    Runnable,(plus an optional name)
  • Thread myFirstThread new Thread(f, My first
    thread)
  • Send the message start to the Thread object
  • myFirstThread.start()

class Foo implements Runnable public void
run() // ... stuff to do ... f new
Foo()
A Thread object must still be made, as its
start() method is still needed.
10
Creating Your Own Threads (6) Comparisons
  • Creating threads by extending the Thread class
  • easier to use in simple applications
  • limited by the fact that your task class must be
    a descendant of Thread.
  • Remember, one can only extend or inherit from a
    single parent class in java
  • Examples
  • If a thread is to start running in the applet,
    you cannot use this method to create a thread.
    The applet cannot inherit from both the Thread
    and Applet classes.
  • Creating threads by implementing the runnable
    interface
  • It is more general, because the Runnable object
    can subclass a class other than Thread
  • By separating the Runnable task from the Thread
    object that executes the task, not only is this
    approach more flexible, but it is applicable to
    the high-level thread management APIs.
  • In general, there isn't much difference between
    the two approaches. Both have the same
    functionality.

11
Thread States Life Cycle of a Thread (1)
  • NEW
  • A new thread begins its life cycle in the new
    state
  • After the creations of Thread instance the thread
    is in this state
  • Remains in this state until program starts the
    thread (the start() method is invocated) ,
    placing it in the runnable state
  • RUNNABLE
  • A thread first enters runnable state after the
    invoking of start() method
  • A thread in this state is executing its task
    running or is available to execute ready
  • WAITING
  • A thread transitions to this state to wait for
    another thread to perform a task
  • A thread transitions back to the runnable state
    only when another thread signals the waiting
    thread to continue executing

12
Thread States Life Cycle of a Thread (2)
  • TIMED WAITING
  • A thread enters this state to wait for another
    thread or for an amount of time to elapse
  • A thread in this state returns to the runnable
    state when it is signaled by another thread (for
    example, when the event it is waiting for occurs)
    or when the timed interval expires whichever
    comes first.
  • Another way to put a thread in this state is to
    put the thread to sleep.
  • TERMINATED
  • A runnable thread enters this state when it
    completes its task ie its run() method has
    finished or thrown an exception

13
Thread States Life Cycle of a Thread (3)
14
Terminating Threads
  • The normal way of terminating a thread
  • When its run method returns
  • How to terminate a running thread?
  • In the initial release of Java, the Thread class
    had a stop method to terminate a thread
  • Deprecated now. It has been found that stopping a
    thread can lead to dangerous situations when
    multiple threads share objects.
  • Instead of simply stopping a thread, you should
    notify the thread that it should be terminated.
  • Setting some internal flag
  • The thread can then periodically query that flag
  • Interrupting a thread
  • A thread should occasionally check whether it
    has been interrupted, by calling the
    isInterrupted() method.
  • However, if a thread is sleeping, it cant
    execute code that checks for interruptions.
    Therefore, the sleep method throws an
    InterruptedException whenever a sleeping thread
    is interrupted.

15
Check for Thread Interruptions
The easiest way to do this is to surround the
entire work portion of the run method with a try
block
  • public void run( )
  • try
  • while(!isInterupted())
  • //do work
  • catch(InterruptedException exception)
  • //clean up

16
Thread Priority
  • Each thread has an assigned priority that is used
    to let more important threads use resources ahead
    of lower-priority resources.
  • The child thread inherits the priority of the
    parent
  • A priority is an integer from 1 to 10 inclusive.
  • 10 is the highest priority MAX_PRIORITY
  • 1 is the lowest priority MIN_PRIORITY.
  • By default, every thread is given priority 5
    (NORM_PRIORITY)
  • How to control the priority?
  • public final void setPriority(int  newPriority)
  • public final int getPriority( )

17
Thread Scheduling
  • Definition
  • execution of multiple threads in some order on a
    single CPU system is called scheduling
  • Java uses fixed-priority scheduling algorithms to
    decide which thread to execute
  • the thread with the highest priority runs first
  • if another thread with a higher priority is
    started, Java makes the lower priority thread
    wait
  • if more than one thread exists with the same
    priority, Java quickly switches between them in
    round-robin fashion BUT only if the operating
    system uses time-slicing
  • Actual Scheduling depends on the Operating system

18
Thread Priorities and Scheduling
19
Multithreading in Swing
  • In general, Swing is not thread safe.
  • Single thread rule
  • Once a Swing component has been realized, all
    code that might affect the state of that
    component should be executed in the
    event-dispatching thread.
  • ---taken from Sun
    Developer Network
  • Definition
  • Realized means that the component's paint()
    method has been or might be called.
  • Top level components setVisible(true), show()
  • Once a window is realized, all components that it
    contains are realized
  • The event-dispatching thread the thread that
    executes drawing and event-handling code
  • the paint() and actionPerformed() methods are
    automatically executed in the event-dispatching
    thread.
  • Another way to execute code in the
    event-dispatching thread is to use the
    SwingUtilities invokeLater() method

20
Multithreading in Swing Example code
  • public static void main(String args)
  • Runnable r new Runnable()
  • public void run()
  • BorderLayoutIntro demo
  • demo new BorderLayoutIntro()
  • demo.startGUI()
  • SwingUtilities.invokeLater(r)
  • public static void invokeLater(Runnable doRun)
  • Causes doRun.run() to be executed
    asynchronously on the AWT event dispatching
    thread
  • This will happen after all pending AWT events
    have been processed.
  • This method should be used when an application
    thread needs to update the GUI.

21
Other useful Thread object methods
22
Other resources
  • JDK API for class Thread
  • http//java.sun.com/docs/books/tutorial/essential/
    concurrency/
  • A Sun tutorial on Java multithreading
  • "Java - How to Program" (Sixth Edition) by Deitel
    and Deitel
Write a Comment
User Comments (0)
About PowerShow.com