Multithreading - PowerPoint PPT Presentation

1 / 35
About This Presentation
Title:

Multithreading

Description:

synchronize if one or more threads will access the same object or field. ... useful, when you want to make sure all threads are finished before you do some cleanup ... – PowerPoint PPT presentation

Number of Views:138
Avg rating:3.0/5.0
Slides: 36
Provided by: michael742
Category:

less

Transcript and Presenter's Notes

Title: Multithreading


1
Multithreading
  • multitasking
  • Example Downloading a file from the internet
    while writing a paper at
  • the same time.
  • thread
  • single sequential flow of control
  • managed by the same Java virtual machine
  • share common memory space
  • thread versus process process
  • managed by the operating system
  • no shared memory space
  • communication just via interprocess communication
    channels

2
Multithreading (cont.)
  • advantages
  • reactive systems
  • continuously monitor arrays of sensors and react
    according to the sensor readings
  • reactive GUI
  • allows to respond to user input immediately even
    if the application is engaged in a time-consuming
    task
  • multi-client servers
  • multiple processors
  • executing threads on different processors in
    parallel

3
Multithreading (cont.)
  • nondeterministic thread ordering
  • multi processors
  • time-sharing

4
Creating and Running Threads
  • Three possibilities
  • extending the Thread class
  • implementing the Runnable interface
  • using anonymous inner classes

5
Thread class
  • class for active objects
  • subclasses of Thread should override the run
    method
  • run hook method
  • implements the interface Runnable
  • implement run
  • start method
  • run should not invoked directly. Doing so would
    cause the method to be executed in the thread of
    the caller, not in a new thread.
  • use the start method to execute a thread

6
Extending the Thread Class
  • public class MyThread extends Thread
  • public void run()
  • System.out.println(Do something cool here.)
  • Thread myThread new MyThread()
  • myThread.start()

7
Implementing the Runnable interface
  • public class MyClass extends SomeOtherClass
  • implements Runnable
  • public MyClass()
  • Thread thread new Thread(this)
  • thread.start()
  • public void run()
  • System.out.println(Do something cool here.)

8
Using anonymous inner classes
  • new Thread()
  • public void run()
  • System.out.println(Do something cool here.)
  • .start()

9
Comparison of the methods
  • Extending the Thread class is easy but uses
    inheritance.
  • Use the Runnable interface if you want to have a
    class that extends another and can also run as a
    thread.
  • Use anonymous inner classes only if the code in
    the run method is very short.

10
Thread safety
  • Safety properties are conditions that should hold
    throughout the lifetime of a program.
  • stipulate that nothing bad should ever happen
  • interrupted threads may leave an object in an
    invalid state
  • public class Maze
  • private int playerX
  • private int playerY
  • public boolean isAtExit()
  • return (playerX 0 playerY 0)
  • public void setPosition(int x, int y)
  • playerX x
  • playerY y

11
Initial state of p playerX 1 playerY 0
Thread B
Thread A
?
p.setPosition(0,1)
?
playerX 0 playerY 0
playerX x
Thread A is pre-empted by Thread B
?
p.isAtExit()
?
returns true
?
playerX 0 playerY 1
playerY y
?
12
Controlling Threads
  • states of a thread
  • new
  • alive
  • runnable
  • blocked
  • dead
  • priorities
  • always runs highest priority thread
  • random choice, among those with same priority
  • preemptive, i.e., a thread of higher priority
    will preempt a thread with lower priority
  • use priorities only to tune the performance of
    programs

13
Alive
yield()
Blocked
Runnable
wait()
start()
notify() notifyAll()
join()
interrupt()
Target finish
sleep()
run() returns
Time out
interrupt()
14
Synchronization
  • public class Maze
  • private int playerX
  • private int playerY
  • public synchronized boolean isAtExit()
  • return (playerX 0 playerY 0)
  • public synchronized void setPosition(int x, int
    y)
  • playerX x
  • playerY y
  • This code is thread-safe.

15
Synchronization (cont.)
  • When the JVM executes a synchronized method, it
    acquires a lock on that
  • object.
  • if one synchronized method owns a lock, no other
    synchronized method can run until the lock is
    released
  • only one lock on an object at a time
  • lock is released when the method is finished

16
Synchronization (cont.)
  • Do not oversynchronize!
  • synchronize if one or more threads will access
    the same object or field.
  • do not synchronize an entire method if only parts
    of the method need to be synchronized
  • public void myMethod()
  • synchronize(this)
  • // code that needs to be synchronized
  • // code that is already thread-safe
  • do not synchronize a method that uses only local
    variables
  • //a method which should not be synchronized
  • public int square(int n)
  • int s n n
  • return s

17
Using sleep()
  • sleep() is a static method of the class Thread.
  • Thread.sleep(1000)
  • causes the currently running thread to sleep for
    1000 (or any amount of time given as an argument)
    miliseconds (state blocked)
  • a sleeping thread does not consume any CPU time
  • when the specified duration of time expires the
    thread returns to the runnable state

18
Using wait() and notify()
  • Problem Thread A should wait on Thread B to
    send a message
  • Solution 1
  • //Thread A
  • public void waitForMessage()
  • while (hasMessage false)
  • Thread.sleep(100)
  • //Thread B
  • public void sendMessage(String message)
  • hasMessage true

19
  • Solution 2
  • //Thread A
  • public synchronized void waitForMessage()
  • try
  • wait()
  • catch (InterruptedException ex)
  • //Thread B
  • public synchronized void sendMessage(String
    message)
  • notify()

20
  • The wait(), notify() and notifyAll() methods are
    defined in the
  • class Object.
  • the wait() method is used in synchronized blocks
    of code.
  • the lock is released and the thread waits to be
    notified (state blocked)
  • the notify() method is also used in synchronized
    blocks of code.
  • notifies on thread waiting on the same lock
    (randomly)
  • waiting thread becomes runnable
  • variants
  • wait for a maximum amount of time wait(100)
  • there is no way to tell whether the wait() method
    returned because of a timeout or because the
    thread was notified
  • notify all threads waiting on the lock
    notifyAll()

21
Using join()
  • The join() method causes a thread to enter the
    blocked state and wait
  • for another thread to finish, at which time it
    will be returned to the
  • runnable state.
  • useful, when you want to make sure all threads
    are finished before you do some cleanup

22
  • public static void main(String args)
  • Thread playerA new Thread()
  • public void run()
  • System.out.println("A started")
  • try Thread.sleep(10000)
  • catch (InterruptedException e)
  • System.out.println("A terminated")
  • Thread playerB new Thread()
  • public void run()
  • System.out.println("B started")
  • try Thread.sleep(15000)
  • catch (InterruptedException e)
  • System.out.println("B terminated")

23
  • playerA.start()
  • playerB.start()
  • try
  • playerA.join()
  • playerB.join()
  • catch (InterruptedException e)
  • System.out.println("Cleanup")

24
Deadlock
  • Deadlock is the result of two threads that stall
    because they are waiting on
  • each other to do something. General situation
  • Thread A acquires lock 1.
  • Thread B acquires lock 2.
  • Thread B waits for lock 1 to be released.
  • Thread A waits for lock 2 to be released.

25
Deadlock - Example
  • MessageHandler a
  • MessageHandler b
  • //Thread A //Thread B
  • ? ?
  • a.waitForMessage() b.waitForMessage()
  • b.sendMessage(...) a.sendMessage(...)
  • ? ?
  • In general, detecting and preventing deadlock is
    difficult.
  • Using the deadlock detector.
  • run your program
  • press Ctrlbreak (DOS box)
  • JVM displays a full thread dumb

26
Liveness
  • Liveness properties stipulate that something
    positive will eventually
  • happen. Examples
  • A certain task will be completed eventually.
  • A thread should always respond to user input.
  • The status of certain systems must be displayed
    and updated constantly.
  • Common types of liveness failures
  • deadlock
  • contention
  • aka starvation or indefinite postponement
  • thread never gets a chance to run
  • sleep() or yield()
  • dormancy
  • blocked thread never released
  • failure to call notify()
  • premature termination

27
Example Thread pool
  • A thread pool is a group of threads designed to
    execute arbitrary tasks.
  • limits the number of threads on the system for
    processor-intensive tasks
  • ThreadPool threadPool new ThreadPool(3)
  • for (int i0 i lt 8 i)
  • threadPool.runTask(createTask(i))
  • threadPool.join()

28
  • private static final Runnable createTask()
  • return new Runnable()
  • public void run()
  • System.out.println("Task " taskID "
    start")
  • // simulate a long-running task
  • try
  • Thread.sleep(500)
  • catch (InterruptedException ex)
  • System.out.println("Task " taskID "
    end")

29
Thread group
  • ThreadPool uses the ThreadGroup class. A
    ThreadGroup is a group of
  • threads and some methods to modify the threads.
  • setDaemon() - changes the daemon status of this
    thread group. A daemon thread group is
    automatically destroyed when its last thread is
    stopped.
  • interrupt() interrupts all threads in this
    thread group.
  • activeCount() - returns an estimate of the number
    of active threads in this thread group.
  • enumerate() - copies into the specified array
    (argument) every active thread in this thread
    group.

30
  • public class ThreadPool extends ThreadGroup
  • private boolean isAlive
  • private LinkedListltRunnablegt taskQueue
    //Java 1.5
  • private static int threadID
  • private static int threadPoolID
  • public ThreadPool(int numThreads)
  • super("ThreadPool-" (threadPoolID))
  • setDaemon(true)
  • isAlive true
  • taskQueue new LinkedListltRunnablegt()
    //Java 1.5
  • for (int i0 iltnumThreads i)
  • new PooledThread().start()

31
  • private class PooledThread extends Thread
  • public PooledThread()
  • super(ThreadPool.this,"PooledThread-"
    (threadID))
  • public void run()
  • while (!isInterrupted())
  • Runnable task null // get a task to
    run
  • try
  • task getTask()
  • catch (InterruptedException ex)
  • if (task null) //if getTask() returned
    null return //or was interrupted close
    this //thread by returning.
  • try //run the task, and eat
    any
  • task.run() //exceptions it
    throws
  • catch (Throwable t)
  • uncaughtException(this, t)

32
  • public synchronized void runTask(Runnable task)
  • if (!isAlive)
  • throw new IllegalStateException()
  • if (task ! null)
  • taskQueue.add(task)
  • notify()
  • protected synchronized Runnable getTask() throws
    InterruptedException
  • while (taskQueue.size() 0)
  • if (!isAlive)
  • return null
  • wait()
  • return taskQueue.removeFirst() //Java
    1.5

33
  • public void join()
  • // notify all waiting threads that this
    ThreadPool is no
  • // longer alive
  • synchronized (this)
  • isAlive false
  • notifyAll()
  • // wait for all threads to finish
  • Thread threads new ThreadactiveCount()
  • int count enumerate(threads)
  • for (int i0 iltcount i)
  • try
  • threadsi.join()
  • catch (InterruptedException ex)

34
  • public synchronized void close()
  • if (isAlive)
  • isAlive false
  • taskQueue.clear()
  • interrupt()

35
An example
  • Task 0 start
  • Task 1 start
  • Task 2 start
  • Task 0 end
  • Task 3 start
  • Task 1 end
  • Task 4 start
  • Task 2 end
  • Task 5 start
  • Task 3 end
  • Task 6 start
  • Task 4 end
  • Task 7 start
  • Task 5 end
  • Task 6 end
  • Task 7 end
  • Press Enter to continue
Write a Comment
User Comments (0)
About PowerShow.com