Multithreading - PowerPoint PPT Presentation

1 / 25
About This Presentation
Title:

Multithreading

Description:

Construct a thread object with the threadname. public Thread() Construct a thread object whose name = 'Thread-' number. void start ... – PowerPoint PPT presentation

Number of Views:59
Avg rating:3.0/5.0
Slides: 26
Provided by: perdanaFs
Category:

less

Transcript and Presenter's Notes

Title: Multithreading


1
Multithreading
2
Outline
  • Introduction
  • Class thread
  • Thread States
  • Scheduling and Priority
  • Thread Synchronization
  • Daemon Thread

3
Introduction
  • One of the characteristics that makes Java a
    powerful programming language is its support of
    multithreaded programming as an integrated part
    of the language.
  • Multithreading is the ability of a program or an
    operating system process to manage its use by
    more than one user at a time and to even manage
    multiple requests by the same user without having
    to have multiple copies of the programming
    running in the computer. It involves multiple
    threads of control within a single program.

4
Introduction
  • A thread is a single sequence of execution
    within a program. Threads allow you to do many
    things at the same time.
  • One of the example of Multithreading is Javas
    automatic garbage collection. The garbage
    collector thread automatically reclaims
    dynamically allocated memory that is no longer
    needed.
  • Furthermore writing multithreaded programming can
    be tricky. Why use threads?

5
Class Thread
  • public Thread(String threadname)
  • Construct a thread object with the threadname
  • public Thread()
  • Construct a thread object whose name
    Thread- number
  • void start()
  • Cause the thread to begin execution. Call run
    method
  • void run()
  • Method to place the work of the thread.

6
Class Thread
  • void sleep(long milisec)
  • Causes the currently executing thread to sleep
    for the specified number of milliseconds.
  • boolean isIinterrupted()
  • Tests whether the thread has been interrupted.
  • void interrupt()
  • Interrupts the thread.
  • boolean isAlive()
  • Test whether start method has been called.

7
Class Thread
  • void join()
  • Waits for the Thread to which the message is
    sent to die before the calling Thread can
    proceed.
  • public class classname extends Thread
  • To add thread functionality to a class, simply
    derive the class from Thread and override the run
    method.
  • public class classname implements Runnable
  • The Runnable interface provides the overhead
    for adding thread functionality to a class.
    Classes that implement the Runnable interface
    provide a run method that is executed by an
    associated thread object that is created
    separately.

8
Thread States
9
Thread States
  • When a thread is first created, it does not
    exist as an independently executing set of
    instructions. Instead, it is a template from
    which an executing thread will be created. This
    state is refer to born state.
  • When the thread start method is called, the
    thread is now enter the ready state.
  • When the system assigns a processor to the
    thread , the thread is in the running state.
  • A thread enters the dead state when its run
    method completes or terminates.

10
Thread States
  • The running thread will enter the block state
    when it issues an input or output request.
  • The running thread will enter sleeping state
    when sleeping method is called. The sleeping
    state will expire after the sleep time expires.
  • The running thread will enter waiting state when
    wait method is called. One thread in the waiting
    state will become ready when notify method is
    called. Every thread in the waiting state will
    become ready when notifyAll method is called.

11
Creating Executing Threads
12
(No Transcript)
13
Output
14
Scheduling and Priority
  • Thread scheduling is the mechanism used to
    determine how runnable threads are allocated CPU
    time.
  • A thread-scheduling mechanism is either
  • preemptive
  • nonpreemptive.

15
Preemptive Scheduling
  • The thread scheduler preempts a running thread
    to allow different threads to execute.
  • A preemptive scheduler can be either time-sliced
    or nontime-sliced. With time-sliced scheduling,
    the scheduler allocates a period of time
    (quantum) that each thread can use the CPU. A
    nontime-sliced scheduling uses other criteria
    such as priority or I/O status to preempt a
    thread.
  • A yield method() is appropriate for a non
    timesliced systems in which a thread would
    complete before another thread (same priority)
    would have opportunity to run.

16
Non-Preemptive Scheduling
  • The non-preemptive scheduler never interrupts a
    running thread, but relies on the running thread
    to yield control of the CPU so that other threads
    may execute.
  • Java scheduler ensures that several equally
    high-priority threads execute for a quantum in
    round-robin fashion.
  • Sometimes, the new high priority threads could
    postpone possibly indefinitely by the execution
    of the lower priority threads, which refer to
    Starvation.

17
Scheduling and Priority
  • Every thread has a priority. When a thread is
    created, it inherits the priority of the thread
    that created it. A thread has a priority in the
    range Thread.MIN_PRIORITY (1) and
    Thread.MAX_PRIORITY (10). By default, each thread
    is given priority Thread.NORM_PRIORITY (5). The
    highest the numbers, the highest the priority.
  • void setPriority(int newPriority)
  • To adjust the threads priority.
  • int getPriority()
  • Returns this thread's priority.

18
Thread Synchronization
  • Every object with synchronized methods is a
    monitor.
  • Java uses monitors to perform synchronization.
    It allows one thread at a time to execute a
    synchronized method on the object.
  • When the synchronized method is invoked, the
    object is locked. All other threads attempting to
    invoke synchronized methods must wait. All these
    threads will call wait method.
  • When a synchronized method finishes executing,
    the lock on the object is released. The highest
    priority ready thread that invoke a synchronized
    method will proceed.

19
Thread Synchronization
  • The thread can notify a waiting thread to become
    ready again so that it can attempt to obtain the
    lock on the monitor object again and then
    execute.
  • Monitor objects maintain a list of all threads
    waiting to enter the monitor object to execute
    synchronized methods.
  • Threads that explicitly invoked wait can only
    proceed when notified via a call by another
    thread to notify or notifyAll.
  • One of the example of thread synchronization is
    thread coordination.

20
Thread Synchronization
  • One of the problem of thread coordination is
    bounded buffer. This problem involves using a
    fixed-size memory buffer to communicate between
    two processes or threads.
  • In order to solve this problem, the following
    requirement must be fulfill
  • When the writer thread attempts to write to a
    full buffer, the writer is suspended until some
    items are removed from the buffer.
  • When the reader thread removes items from the
    full buffer, the writer thread is notified of the
    buffer's changed condition and may continue
    writing.

21
Thread Synchronization
  • When the reader thread attempts to read from an
    empty buffer, the reader is suspended until some
    items are added to the buffer.
  • When the writer adds items to the empty buffer,
    the reader thread is notified of the buffer's
    changed condition and may continue reading.
  • Shared data can get corrupted if we do not
    synchronize access among multiple threads.
  • By using a circular buffer, we can perform
    synchronize access more optimally.

22
Daemon Threads
  • A Daemon thread is a thread that providing
    service to other threads and it runs in the
    background.
  • Unlike conventional user threads, daemon threads
    do not prevent a program from terminating.
  • The garbage collection thread is one of the
    example of daemon thread
  • When only daemon threads remain alive, the Java
    virtual machine process exits.
  • void setDaemon(boolean on)
  • Marks this thread as either a daemon thread
    (true) or a user thread (false).

23
Contoh animasi
  • import javax.swing.
  • import java.awt.
  • public class Animasi extends JApplet implements
    Runnable
  • private Thread animasi
  • private static final int bilImej 8
  • private Image gambar new Image bilImej
  • private int frame 1
  • public void init()
  • /memuatkan imej/
  • for(int i 1 i lt bilImej i )
  • gambari-1 getImage(getDocumentBase(),image/T
    i .gif)

24
  • public void start()
  • animasi new Thread(this)
  • animasi.start()
  • public void run()
  • while(Thread.currentThread()animasi)
  • repaint()
  • try
  • Thread.sleep(500) // tunggu 500 milisaat
  • catch (InterruptedException e)
  • break
  • frame

25
  • /dilaksanakan apabila aplet tidak kelihatan/
  • public void stop()
  • animasi null
  • / memaparkan nombor frame dan imej/
  • public void paint (Graphics g)
  • super.paint(g)
  • Graphics2D g2 (Graphics2D) g
  • g2.drawImage (gambarframebilImej, 10,
    10,this)
  • g2.drawString(Frame frame, 20, 80)
Write a Comment
User Comments (0)
About PowerShow.com