Threads and Java

download Threads and Java

of 34

Transcript of Threads and Java

  • 8/7/2019 Threads and Java

    1/34

  • 8/7/2019 Threads and Java

    2/34

    TOPICS

    Task, Process Background

    Concurrency

    Threads

    LifeCycle of Threads

    Thread Priorities & Scheduling

    Creating and Executing Threads

    Running Threads Sleeping Threads

    Thread Trouble

    2

  • 8/7/2019 Threads and Java

    3/34

    TASK, PROCESS BACKGROUND

    An application written Start to End

    You know every step

    Know what follows Software LifecycleManufacturing processes

    Would you be doing only one work at any time?

    Probably in a class like this..

    Moms work?

    3

  • 8/7/2019 Threads and Java

    4/34

    MANY TASKS

    Many activities at the same time

    As humans we can do probably 4 or 5 activities

    How about computers?

    Early operating system - DOS (disk OS), Windows 3.1, early MAC version, 1st

    gen computers performed single tasks. Once completed you do the next.

    BATCH processing

    Many Applications - Round Robin

    Why wait for one application? Not very efficient

    Important tasks will on hold

    4

  • 8/7/2019 Threads and Java

    5/34

    CONCURRENCY (OR MULTI-TASKING)

    From a command window you can run one

    Application at a time. One process at one

    time.

    After the first application has been

    executed the next application will be

    executed.

    And then the next.

    So we create batch files

    Do you want spend time waiting for one

    task to be completed before your

    application runs?

    Remember, without the previous

    application your program will not run.

    5

  • 8/7/2019 Threads and Java

    6/34

    CONCURRENCY (OR MULTI-TASKING)

    Operating System vendors introduced

    multi-tasking

    A process for each application to be

    executed

    Let many processes run but in equal

    chunks of time Time Slices

    Each process has been allocatedprogram and data space that will notaffect another process

    6

  • 8/7/2019 Threads and Java

    7/34

    CONCURRENCY (OR MULTI-TASKING)

    Operating System vendors introduced

    multi-tasking

    Let many applications run but in equalchunks of time Time Slices

    Not good, all activities are just set time

    Priorities introduced, urgent tasks HIGH priority

    Timer expiration

    others have LOWER priority

    7

  • 8/7/2019 Threads and Java

    8/34

    PROCESSES

    Many times, an application package will

    contain many associated executables

    An OS does not identify the various

    executables as belonging to one package

    So they run as different processes.

    8

  • 8/7/2019 Threads and Java

    9/34

    PROCESSES (CONTD.)

    Your main application isdependent on anotherprocess or application ortask

    A layered architectureof application

    development Waiting for data or

    state or event

    Your Application is inwaiting statehow long

    YOU ARE STUCK

    You need Concurrent programming

    Flexibility to do things simultaneously

    No need to wait

    Processes create new process.

    Creating new process is heavy

    Need more resources memory

    How about a process that will not require

    new memory or resources allocated.

    Something that can run within the same

    process

    9

  • 8/7/2019 Threads and Java

    10/34

    THREADS TO PROCESSES RESCUE

    10

  • 8/7/2019 Threads and Java

    11/34

    WHY A JAVA THREAD?

    No other languages, except ADA, have thread

    support

    Portability of Java code Need not worry about any overheads of initialization

    and managing of resources of each Operating system

    (JVM does the remaining part).

    11

  • 8/7/2019 Threads and Java

    12/34

  • 8/7/2019 Threads and Java

    13/34

    THREAD STATES

    New Beginning of Thread life. Not ready for execution until programs

    moves state to runnable

    Runnable

    Task is being executed Data dependency on other threads

    Waiting just wait for the other thread completion

    Timed Waiting (Sleeping thread) wait for either expiration of timer or the other thread completion

    Blocked Wait for long time

    Terminated End of life

    13

  • 8/7/2019 Threads and Java

    14/34

    LET US CREATE THREADS

    A thread is associated with an instance of a class Thread.

    Two basic strategies for concurrent application

    To directly control thread creation and management

    Instantiate the thread when needed - asynchronous

    Abstract thread management from rest of you

    application using extractor

    Create instances of Thread

    Extend the thread class and override its run() method

    Implement a Runnable object

    14

  • 8/7/2019 Threads and Java

    15/34

    CREATING RUNNABLE OBJECTS

    public class HelloRunnable implements Runnable

    {

    @Override

    public void run()

    {

    System.out.println("Hello from a thread!");}

    public void run(Strings arg[])

    {

    }

    public static void main(String args[])

    {

    // just started a thread

    (new Thread( new HelloRunnable() ) ).start();

    // Create a Runnable instance

    HelloRunnable HR1 = new HelloRunnable();

    // We need to get a thread for the runnable created

    Thread THR1 = new Thread(HR1);

    }

    } 15

  • 8/7/2019 Threads and Java

    16/34

    EXTENDING THE THREAD

    public class HelloThread extends Thread

    { static int j =0;

    public void run()

    {

    System.out.println("Hello from a thread #+j+++!");

    }

    public static void main(String args[])

    {(new HelloThread() ).start();

    HelloThread HT = new HelloThread();

    HT.start();

    try {

    HT.sleep(3999L);

    }

    catch (InterruptedExceptione)

    {e.printStackTrace();

    }

    }

    }

    Your Output:

    Hello from a thread #0!

    Hello from a thread #1!

    16

  • 8/7/2019 Threads and Java

    17/34

    THREAD CONTROL METHODSMETHOD Name Method Desc Notes

    setName(String ThreadName) Assign a Name for Thread

    getName Retrieve the name of Thread

    setPriority(int newPriority) Change priority of thread Java range

    MAX_PRIORITY = 10

    MIN_PRIORITY = 1

    getPriority() Read current priority

    currentThread() Get current thread reference

    start()

    stop()/ stop(throwable t)/

    stop1()

    run() Subclasses will override this method

    Your program specific code goes here

    Sleep(long millis),Sleep(long millis, int nano )

    Sleep in period of millis

    Yield Willingly allow thread to give up processor

    Suspend/resume Allow thread to pause and restart

    IsAlive() Check if thread is alive

    Join()

    STOP Why we should not use itBecause it is inherently unsafe. Stopping a thread causes

    it to unlock all the monitors that it has locked. (The monitors

    are unlocked as the ThreadDeath exception propagates up

    the stack.) If any of the objects previously protected by these

    monitors were in an inconsistent state, other threads may

    now view these objects in an inconsistent state. Such objects

    are said to be damaged.

    When threads operate on damaged objects, arbitrary

    behavior can result. This behavior may be subtle and difficult

    to detect, or it may be pronounced. Unlike other unchecked

    exceptions,ThreadDeathkills threads silently; thus, the user has no

    warning that his program may be corrupted. The corruption

    can manifest itself at any time after the actual damage

    occurs,

    even hours or days in the future.

    SUSPEND/RESUME are deprecatedThread.suspend is inherently deadlock-prone. If the

    target thread holds a lock on the monitor protecting acritical system resource when it is suspended, no thread

    can access this resource until the target thread is

    resumed. If the thread that would resume the target

    thread attempts to lock this monitor prior to calling

    resume, deadlock results. Such deadlocks typically

    manifest themselves as "frozen" processes.

    17

  • 8/7/2019 Threads and Java

    18/34

    THREADS SLEEP TOO!

    Thestatic method 'sleep( )

    Makes the current thread stop execution for an amount of time

    The unit of time is milliseconds (ms = 1/1000 of a sec)

    A checked exception called 'InterruptedException'

    is thrown by the sleep() method if another process attempts to interrupt

    the thread before the specified time-interval is over.

    This Exception should be handled when the sleep method is used.

    We have to use try{.}catch{} blocks

    18

  • 8/7/2019 Threads and Java

    19/34

    SLEEPING THREADS

    public class HelloRunnable implements Runnable

    {

    @Override

    public void run()

    {

    System.out.println("Hello from a thread!");

    try { Thread.sleep(1000L); }

    catch(InterruptedExceptione)

    {

    System.out.println( Terminated prematurely due to Exception.);

    }

    }

    public void run(Strings arg[])

    {

    }

    public static void main(String args[])

    {

    // just started a thread

    (new Thread( new HelloRunnable() ) ).start();

    // Create a Runnable instance

    HelloRunnableHR1 = new HelloRunnable();

    // We need to get a thread for the runnable created

    Thread THR1 = new Thread(HR1);

    }

    }

    19

  • 8/7/2019 Threads and Java

    20/34

    THREAD JOIN()

    classMyThread implements Runnable {

    String name; // name of thread

    Thread t;

    MyThread(Stringthreadname) {

    name = threadname;

    t = newThread(this, name);

    System.out.println("Newthread: " + t);

    t.start();}

    publicvoid run() {

    try {

    for (int i = 5; i > 0; i--) {

    System.out.println(name+ ": " + i);

    Thread.sleep(1000);

    }

    } catch (InterruptedExceptione) {

    System.out.println(name+ " interrupted.");

    }System.out.println(name+ " exiting.");

    }

    }

    publicclass MainClass {

    publicstatic void main(String args[]) {

    MyThread ob1 = new MyThread("One");

    MyThread ob2 = new MyThread("Two");

    MyThread ob3 = new MyThread("Three");

    System.out.println("ThreadOne is alive: " + ob1.t.isAlive());

    System.out.println("ThreadTwo is alive: " + ob2.t.isAlive());

    System.out.println("ThreadThree is alive: " + ob3.t.isAlive());

    try {

    System.out.println("Waiting for threads to finish.");

    ob1.t.join();

    ob2.t.join();

    ob3.t.join();

    } catch (InterruptedExceptione) {

    System.out.println("Mainthread Interrupted");

    }

    System.out.println("ThreadOne is alive: " + ob1.t.isAlive());

    System.out.println("ThreadTwo is alive: " + ob2.t.isAlive());System.out.println("ThreadThree is alive: " + ob3.t.isAlive());

    System.out.println("Mainthread exiting.");

    }

    }

    Thread One is alive: trueThread Two is alive: trueThread Three is alive: trueWaiting for threads to finish.One: 5

    Three: 5

    One: 4

    Three: 4

    One: 3

    Three: 3One: 2

    Three: 2

    One: 1Three: 1One exiting.Three exiting.Two: 5

    Two: 4

    Two: 3Two: 2

    Two: 1Two exiting.Thread One is alive: falseThread Two is alive: falseThread Three is alive: falseMain thread exiting.

    20

  • 8/7/2019 Threads and Java

    21/34

  • 8/7/2019 Threads and Java

    22/34

    SYNCHRONIZATION - MONITOR

    Mutual Exclusion Associated with one or block lines of codes

    The lines of codes must be executed in that order and not interruptible

    The corresponding thread acquires the lock

    All other threads will wait and serviced in the order

    Co-operation

    Desirable when one thread is responsible for updating whileanother thread needs updated data

    Thread(s) needing updated data will request wait() request andthread remains in wait state

    Thread updating data will issue Notify or Notify All andreleases monitor

    22

  • 8/7/2019 Threads and Java

    23/34

    SYNCHRONIZATION

    Synchronized Blocks or statements

    format

    synchronized ( object )

    {

    statements

    } // end synchronized statement

    Typically your object will be the this operator, if we aresynchronizing in that objects.

    public void set( int value ) throws InterruptException

    {

    // place value into buffer

    // while there are no empty locations, place thread in waitingstate

    Synchronized(this)

    {

    buffer = value; // set new buffer value

    // indicate producer cannot store another value

    // until consumer retrieves current buffer value

    occupied = true;

    displayState( "Producer writes " + buffer );

    notifyAll(); // tell waiting thread(s) to enter runnable state

    }

    }

    Synchronized Methods

    synchronized SomeMethod()

    {

    // Method body

    }

    public synchronized void set( int value ) throws InteruptException

    {

    // place value into buffer

    // while there are no empty locations, place thread in waitingstate

    buffer = value; // set new buffer value

    // indicate producer cannot store another value

    // until consumer retrieves current buffer value

    occupied = true;

    displayState( "Producer writes " + buffer );

    notifyAll(); // tell waiting thread(s) to enter runnable state

    }

    23

  • 8/7/2019 Threads and Java

    24/34

    INTER-THREAD COMMUNICATIONS

    public class Producer implements Runnable {

    private Drop drop;

    public Producer(Drop drop) {

    this.drop = drop;

    }

    public void run()

    {

    String importantInfo[] = {

    "Mares eat oats",

    "Does eat oats",

    "Little lambs eat ivy",

    "A kid will eat ivy too };

    Random random = new Random();

    for (int i = 0; i < importantInfo.length; i++) \

    {drop.put(importantInfo[i]);

    try {

    Thread.sleep(random.nextInt(5000));

    } catch (InterruptedException e) {}

    }

    drop.put("DONE");

    }

    }

    public class Consumer implements Runnable {

    private Drop drop;

    public Consumer(Drop drop) {

    this.drop = drop;

    }

    public void run()

    {Random random = new Random();

    for (String message = drop.take();

    !message.equals("DONE");

    message = drop.take() )

    {

    System.out.format("MESSAGERECEIVED:

    %s%n", message);

    try {Thread.sleep(random.nextInt(5000));

    } catch (InterruptedException e) {}

    }

    }

    }

    24

  • 8/7/2019 Threads and Java

    25/34

    INTER-THREAD COMMUNICATIONS

    (CONTD)public class Drop {

    //Message sent from producer to consumer.

    private String message;

    //True if consumer should wait for producer to send

    message, false

    //if producer should wait for consumer to retrieve

    message.

    private boolean empty = true;

    public synchronized String take() {

    //Wait until message is available.

    while (empty) {

    try {

    wait();

    } catch (InterruptedException e) {}

    }

    //Toggle status.

    empty = true;

    //Notify producer that status has changed.

    notifyAll();

    return message;

    }

    public synchronized void put(String message) {

    //Wait until message has been retrieved.

    while (!empty) {

    try {

    wait();

    } catch (InterruptedException e) {}

    }

    //Toggle status.

    empty = false;

    //Store message.

    this.message= message;

    //Notify consumer that status has changed.

    notifyAll();

    }

    }

    public class ProducerConsumerExample{

    public static void main(String[] args) {

    Drop drop = new Drop();

    (new Thread(new Producer(drop))).start();

    (new Thread(new Consumer(drop))).start();

    }

    }

    25

  • 8/7/2019 Threads and Java

    26/34

    DEADLOCK WHAT IS IT?

    When a waiting thread (let us call this thread1)cannot proceed because it is waiting (eitherdirectly or indirectly) for another thread (let us call

    this thread2) to proceed, while simultaneouslythread2 cannot proceed because it is waiting(either directly or indirectly) for thread1 toproceed.

    The two threads are waiting for each other, so theactions that would enable each thread to continueexecution can never occur.

    26

  • 8/7/2019 Threads and Java

    27/34

    D E A DL O C K

    27

  • 8/7/2019 Threads and Java

    28/34

    D E A DL O C K

    28

  • 8/7/2019 Threads and Java

    29/34

    D E A DL O C K

    29

  • 8/7/2019 Threads and Java

    30/34

    D E A DL O C K

    30

  • 8/7/2019 Threads and Java

    31/34

    D E A DL O C K

    31

  • 8/7/2019 Threads and Java

    32/34

    DEADLOCK HOW TO RESOLVE?

    There is no best solution.

    Best known way of resolving the deadlock is

    resource ordering or restructuring the

    programming logic.

    32

  • 8/7/2019 Threads and Java

    33/34

    C0NCLUSION Multitasking and Processes

    Thread allow parallelization in our programming activity and logics.

    Thread do not require new memory and hence termed Lightweight

    Lifecycle of a Thread, and thread states new, runnable, wait, timed wait, blocked, terminated

    Creating Threads - runnable and thread extends, a third kind extractors

    Threads can wait while the remaining program can continue to execute

    Threads can wait for another thread to complete using the join method

    Use of synchronization for blocks of code or a method to allow us to manipulate data and preventingblocking.

    We can perform inter-thread communication using a shared code and synchronization

    Deadlocks can still occur when two threads are waiting for an object to be released by the otherthread ( could be directly or indirectly)

    33

  • 8/7/2019 Threads and Java

    34/34

    THANK YOU

    Q & A

    34