COP3252 Advanced Java Programming - PowerPoint PPT Presentation

1 / 20
About This Presentation
Title:

COP3252 Advanced Java Programming

Description:

(Sources : These lecture notes rely heavily on information from the course ... join(); causes the current thread to pause execution until t's thread terminates. ... – PowerPoint PPT presentation

Number of Views:76
Avg rating:3.0/5.0
Slides: 21
Provided by: UoD
Category:

less

Transcript and Presenter's Notes

Title: COP3252 Advanced Java Programming


1
COP3252Advanced Java Programming
  • 25-Mar-08
  • Lecture Set 18
  • Threading (Concurrency)
  • (Sources These lecture notes rely heavily on
    information from the course textbook and from the
    Sun Online Java Tutorials)

2
Threading (concurrency)
  • Allows us to write software that completely
    multiple tasks at the same time
  • Example Downloading a streaming audio file
    while simultaneously playing another audio file.

3
Processes and Threads
  • Two basic units of execution
  • Processes
  • self-contained execution environment
  • Has its own memory space and resources
  • JVM usually runs as a single process
  • Threads
  • lightweight processes
  • Requires fewer resources than a new process
  • Exist within a process (every process has at
    least one thread)
  • Share the processs resources
  • Process creation will not be discussed in this
    class.

4
Threads
  • Threads are associated with an instance of the
    class Thread
  • (see http//java.sun.com/javase/6/docs/api/java/
    lang/Thread.html
  • Each time an application needs to initiate an
    asynchronous task, instantiate Thread

5
Using Threads
  • Two ways to define the code that will run in a
    thread
  • Runnable Objects
  • Interface that defines a single method (run)
    meant to contain the code executed in the thread.
  • Runnable object is passed to the Thread
    constructor
  • Subclass Thread
  • Application can Subclass thread and provide its
    own implementation of run.

6
Runnable and Subclassing Thread
  • public class TestRunnable implements Runnable
  • public void run()
  • System.out.println(Test")
  • public static void main(String args)
  • (new Thread(new TestRunnable())).start()
  • public class TestThread extends Thread
  • public void run()
  • System.out.println(Test")
  • public static void main(String args)
  • (new TestThread()).start()

7
Runnable vs Subclassing Thread
  • Runnable
  • More general because Runnable object can subclass
    a class other than Thread
  • More flexible for the same reason
  • Subclassing Thread
  • Easier to use in simple applications .

8
Sleep and Interrupts
  • sleep
  • Causes the current thread to suspend execution
    for a specified period
  • Makes processor time available for other threads
  • Can be used to pace an application
  • This has been seen in previous class examples
  • Interrupt
  • Indication to a thread that it should stop what
    it is doing and do something else.
  • Programmer decides action (usually terminate)
  • Thread sends interrupt by invoking method
    interrupt on Thread object

9
Supporting Interruption
  • For interrupt to work, thread must support
    interruption
  • Two general ways
  • Invoking methods that throw InterruptedException
  • Check for interruption via Thread.interrupted()

10
Supporting Interruption
  • for (int i 0 i lt importantInfo.length i)
  • try Thread.sleep(4000)
  • catch (InterruptedException e) return
  • System.out.println(something)
  • --------------------------------------------------
    --------------
  • for (int i 0 i lt inputs.length i)
  • heavyWork()
  • if (Thread.interrupted()) return
  • --------------------------------------------------
    --------------
  • If (Thread.interrupted())
  • thrown new InterruptedException()

11
Interrupt Status Flag
  • Interrupt mechanism is implemented using internal
    interrupt status flag.
  • Flag is set when Thread.interrupt is invoked.
  • When thread checks for interrupt by invoking
    static method Thread.interrupted, interrupt
    status (flag) is cleared.
  • Non-static Thread.isInterrupted, used by a thread
    to query interrupt status of another thread, does
    not change flag.

12
Joins
  • join method allows one thread to wait for the
    completion of another.
  • If t is a Thread object whose thread is currently
    executing, t.join() causes the current thread to
    pause execution until ts thread terminates.
  • Overloads of join allow the programmer to specify
    a waiting period.

13
Simple Threading Example
  • See SimpleThreads.java (from Sun tutorials)

14
ProgressMonitor Class
  • Used to report on the status of a time-consuming
    task.
  • Special Swing class
  • Displays a pop-up window that shows a progress
    bar
  • Allows user to see amount completed, or cancel
    the task.
  • See SampleProgress.java

15
Thread-Safe GUIs
  • Thread-safe Two separate threads of execution
    can access the control as the same time without
    the developer having to worry about threads
    interfering with one another.
  • A lot of thread safety has been built into AWT
    and other elements of the JDK.
  • This safety increased overhead --- and makes
    applications a bit sluggish in some instances.

16
Swing and Thread Safety
  • When it came time to develop Swing, thread speed
    won out over thread safety.
  • Developer is now responsible for adding code to
    insure no ill effects occur from accessing
    components from multiple threads.

17
Bad Threading
  • See ThreadSafetyExample1.java
  • This example is not thread safe
  • Problem Thread updates contents of list box
    continuously. As thread updates box, drawing
    thread in Swing also accesses the elements to
    keep the GUI representation update. This causes a
    cascading series of exceptions.

18
Good threading
  • How can you prevent the error in the previous
    example?
  • Use one of the static methods in the EventQueue
    class invokeLater() or invokeAndWait()
  • Methods take a Thread as their parameter and are
    responsible for executing the thread in sync with
    the main Swing thread.
  • These two methods determine how you want the
    update to occur.
  • invokeLater() returns immediately, placing the
    update code in the regular even queue of Swing.
  • Updating takes places as soon as possible, but
    doesnt make code wait for update to occur
  • invokeAndWait() wont return until the update is
    complete.

19
Good threading
  • ThreadSafetyExample2.java
  • invokeLater() is used to update the Swing
    controls contents
  • No exceptions occur because both update and draw
    threads are no longer in conflict.

20
ProgressMonitorInputStream
  • Input stream filter that uses a ProgressMonitor
    to check the progress of the reading of an input
    stream.
  • See ProgressInputSample.java
Write a Comment
User Comments (0)
About PowerShow.com