8 threads

Upload: suresh1130

Post on 30-May-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 8 Threads

    1/74

    1Java

    Threads

  • 8/14/2019 8 Threads

    2/74

    2Java

    Naming threads10

    Behind the scene9

    Another way to create thread8

    Complete Example7

    Syntax for creating Thread6

    Others places where threads play important roles5

    Thread and process4

    Thread3

    Concurrent execution2

    Thread in a simple java program1

    Contents

  • 8/14/2019 8 Threads

    3/74

    3Java

    Locking20

    Solution to the Account problem19

    Synchronization18

    IllegalArgumentException17

    Selfish threads16

    Thread priorities15

    Interruption14

    join()13

    sleep()12

    Lifecycle11

    Contents

  • 8/14/2019 8 Threads

    4/74

    4Java

    Challenge your mind28Daemon threads27

    wait() and notify()26

    Methods of Object class used for thread communication25

    Inter-thread communication24Deadlocks23

    A few more points !22

    Synchronized Code21

    Contents

  • 8/14/2019 8 Threads

    5/74

    5Java

    Know

    What threads are

    The difference between thread andprocess

    How to create threads in java

  • 8/14/2019 8 Threads

    6/74

    6Java

    Know

    The Thread life cycle

    The Thread class methods sleep(),interrupt(), yield() and join() do

    Thread priority

    Synchronization

    Inter-Thread-Communication

    About daemon threads

  • 8/14/2019 8 Threads

    7/74

    7Java

    Be Able To

    Implement threads java programs

  • 8/14/2019 8 Threads

    8/74

    8Java

    Thread in a simple java program

    public class ThreadTest{

    public static void main(String s[]){

    System.out.println(Hello);System.out.println(

    Thread.currentThread().getName());

    }}

    Prints : main Folder 1

  • 8/14/2019 8 Threads

    9/74

    9Java

    Concurrent execution

    // include all necessary imports

    public class PrintQuestionPaper{

    public static void main(String s[]){

    for(int i=0;i

  • 8/14/2019 8 Threads

    10/74

    10Java

    Thread

    Sun defines a thread as a singlesequential flow of control within aprogram.

    It is sometimes referred to as anexecution context or a lightweight process.

    Thread based multitasking environmentsallow a single program to perform two ormore tasks simultaneously.

  • 8/14/2019 8 Threads

    11/74

    11Java

    Multitasking is multiprocessing

    A process is a thread.

    I am confused!

    OS level Multitasking are of twotypes- process based and thread-based. A process is program that isexecuting. Executing multipleprocesses simultaneously ismultiprocessing. Process is heavy

    weight because it requires separateaddress space. Interprocesscommunication and contextswitching from one process toanother process are expensive.

  • 8/14/2019 8 Threads

    12/74

    12Java

    Thread and process

    Threads are the code sequence that execute

    within a process.

    So they share the same address space and a

    data. Inter-thread communication and contextswitching inexpensive.

    Process: A

    Java Program

    Threads or a

    independent path

    of execution.

  • 8/14/2019 8 Threads

    13/74

    13Java

    I never knew one processor can

    execute multiple tasks

    simultaneously !

    No no ! You dont get it. One processor

    can do only one task at a time. We aretalking about task switching for example

    the task that is waiting for IO to finish can

    give up the processor to the to some

    other task instead of wasting processors

    precious time. Of course it ultimately

    depends on what kind of threading your

    OS supports- Preemptive or Non-

    Preemptive .

  • 8/14/2019 8 Threads

    14/74

    14Java

    Others places where threads play

    important roles In client-server based systems, the server

    program creates threads that allows it torespond to multiple users at the same time.

    GUI programs have a separate thread togather users interface events from the hostOS.

    Do other things while waiting for slow I/O

    operation. Animations

  • 8/14/2019 8 Threads

    15/74

    15Java

    Syntax for creating Thread

    class SimpleThread extends Thread {

    public void run(){

    /* code that is executed when

    thread executes */

    }}

    Thread t= new SimpleThread();

    t.start();

    1. Inherit from

    the Threadclass

    2. Override run method

    Calls run() methodCreates thread

    orjava.lang.Thread

  • 8/14/2019 8 Threads

    16/74

    16Java

    class Thread{public void start(){// create OS level thread

    run(); }public void run(){}}

    class SimpleThread {public void run(){}}

    SimpleThread c= new SimpleThread();

    c.start();1

    2

  • 8/14/2019 8 Threads

    17/74

    17Java

    (Its my turn to ask now.)

    So, what will happen if you

    call run() method instead of

    start() method ? Think about

    it. If you cannot answer this

    now, wait. There is anotherhint coming up shortly.

  • 8/14/2019 8 Threads

    18/74

  • 8/14/2019 8 Threads

    19/74

    19Java

    public boolean prime(){

    for(int i=2;i

  • 8/14/2019 8 Threads

    20/74

    20Java

    public static void main(String str[]){PrimeOddThread c= new PrimeOddThread ();

    c.num=2;

    c.start();

    if(c.odd())System.out.println("Odd");

    elseSystem.out.println("Even"); }

    }

    Thread no. 1

    Thread no. 2

  • 8/14/2019 8 Threads

    21/74

    21Java

    You can never guarantee whether

    Even will be printed orPrime first.It is totally up to the OS thread

    scheduler to choose which thread

    to execute first.

    What will happen if you call run()

    method instead of start() method ?

  • 8/14/2019 8 Threads

    22/74

    22Java

    Another way to create thread

    class SimpleThreadR implementsRunnable{

    public void run(){}

    }

    Thread t=new Thread(new SimpleThreadR() );

    t.start();

    Creation of thread using a

    constructor that expects a

    Runnable object

    Calls run method of theRunnable instance

    passed via constructor

    i t f R bl {

  • 8/14/2019 8 Threads

    23/74

    Behind the scene

    class Thread implements Runnable{

    private Runnable target;public Thread(Runnable target){}public void start(){// create OS level thread

    run(); }public void run(){if (target != null){target.run(); }}

    class SimpleThreadRimplements Runnable{

    public void run(){}}

    interface Runnable{public void run();}

    Thread t=new Thread(newSimpleThreadR() );

    t.start();}

  • 8/14/2019 8 Threads

    24/74

    24Java

    Let us try to implement

    the PrimeOddThread

    class using Runnableinterface.

    Folder 3

  • 8/14/2019 8 Threads

    25/74

    25Java

    Can you list down all

    the methods and

    constructors of

    Thread class we

    have covered so far?

    Did you notice the usage

    of interface ? This is howinterface can be used as

    a callback.

  • 8/14/2019 8 Threads

    26/74

    26Java

    Naming threads Using Constructors :

    Thread(Runnable target, String name)

    Methods :

    final void setName(String name)

    final String getName()

    To find out which thread is running rightnow:

    Thread.currentThread().getName();static Thread currentThread()

    returns the current thread.

  • 8/14/2019 8 Threads

    27/74

    27Java

    Lifecycle

    new ready running

    Waiting /Blocked

    deadstart() run()

    sleep(), wait()

    Waiting for IO device

    After run()method

    completes

    yield()

    Up to the thread scheduler to pick a

    thread for execution from ready state.

  • 8/14/2019 8 Threads

    28/74

    28Java

    If I start two threads one afteranother like the code below, then

    can we guarantee that the t1 thread

    will execute first and then the t2?

    psvm(){

    Thread t1= newThread(newSimpleThreadR() );Thread t2= new

    Thread(newSimpleThreadR() );t1.start();t2.start();}

  • 8/14/2019 8 Threads

    29/74

    29Java

    After t1 has been created there are

    two active threads - main thread and

    t1. Now let us say that thread

    scheduler chooses t1. In that case

    what you said is right- t1 executesbefore t2. But now let us say main

    executes, then t2 gets created. So,

    now we have three threads- main, t1,

    t2. If thread scheduler chooses t2 thenhere is a chance that t2 executes

    before t1!

  • 8/14/2019 8 Threads

    30/74

    30Java

    sleep()

    static void sleep(long millis) throwsInterruptedException static void sleep(long millis,int nanos) throws InterruptedException

    Example:public class Appear implementsRunnable{

    char c[]={H',E',L',L,O};public void run() {

    Folder 4

  • 8/14/2019 8 Threads

    31/74

    31Java

    int i=0;

    try{

    while (i

  • 8/14/2019 8 Threads

    32/74

    32Java

    join()

    final void join() throwsInterruptedException

    final void join(long millis) throwsInterruptedException

    final void join(long millis,

    int nanos) throws InterruptedException

  • 8/14/2019 8 Threads

    33/74

    33Java

    class Join implements Runnable{

    int num;

    public void run() {

    if( prime())System.out.print("Prime");

    else System.out.print("Non-Prime");}

    public boolean prime(){

    for(int i=2;i

  • 8/14/2019 8 Threads

    34/74

    34Java

    public boolean odd(){

    if(num%2==0)return false;

    else return true; }

    public static void main(String str[]){

    Join s=new Join();

    Thread t= new Thread(s);

    s.num=55;

    t.start();

    boolean b=s.odd();

  • 8/14/2019 8 Threads

    35/74

    35Java

    try{ t.join();

    }catch(InterruptedException e){

    System.out.println("main interrupted");}

    if(b)

    System.out.print(" and Odd");

    elseSystem.out.print("and Even");

    } }

    main thread waits for t

    to finish

  • 8/14/2019 8 Threads

    36/74

    36Java

    Are there any chances of you

    letting us know why sleep() andjoin() methods throw this

    InterruptedException.

  • 8/14/2019 8 Threads

    37/74

    37Java

    Interruption

    A thread can be interrupted by calling interrupt ()

    method on it.

    If this thread is blocked on account of sleep() or join()

    methods, then when interrupt method is called, its

    interrupt status will be cleared and it will receive anInterruptedException.

    void interrupt()

    static boolean interrupted()boolean isInterrupted()

  • 8/14/2019 8 Threads

    38/74

    38Java

    Why will I want a thread

    to be interrupted ?

    Consider a run() method that runs

    continuously in a while loop. If the thread

    is sleeping or waiting then it cant

    actively check whether it should continue

    or terminate. This is were interrupt()

    method comes in. When interrupt()

    method is called on a thread object that iscurrently blocked, the blocking call (such

    as sleep/ join) is terminated by an

    InterruptedException.

  • 8/14/2019 8 Threads

    39/74

    39Java

    Thread priorities

    A thread is always associated with a priority (anumber between 1 and 10, 10 being the highest).

    A thread with a higher priority will run before thethread with lower priority.

    final void setPriority(int newPriority)

    final int getPriority()

    Static constants to set priorities:

    Thread.MIN_PRIORITY (1)Thread.NORM_PRIORITY (5): default

    Thread.MAX_PRIORITY (10)

  • 8/14/2019 8 Threads

    40/74

    40Java

    Selfish threads

    In non-pre-emptive OS, a thread, which executes

    with high priority and has long execution time, doesnot voluntarily leave the CPU for the other threadswith similar priority, such threads are selfish thread.

    It is recommended that threads with high priority

    (be unselfish) call Thread.sleep() or Thread. yield()method.

    static void yield()

    This method causes the currently executingthread object to temporarily pause and allow otherthreads to execute.

  • 8/14/2019 8 Threads

    41/74

    41Java

    Illegal Argument Exception

    This is a RunTimeException and it indicates that

    a method has been passed an illegal or

    inappropriate argument.

    The setPriority(int newPriority)method cantake values between 1 to 10. Any other int value

    will result inIllegalArgumentExceptionexception

  • 8/14/2019 8 Threads

    42/74

    42Java

    Synchronization

    Account

    money: Rs.1000

    Thread A calls withdraw(500)

    Thread B calls withdraw(750)

    Thread A waits for the transaction to complete

    Thread B waits for the transaction to complete

    Account

    money: Rs.-250

    Thread A updates the money to (1000-500)=500

    Thread B updates the money to 500-750=-250

    Code

  • 8/14/2019 8 Threads

    43/74

    43Java

    public class ThreadTest implements Runnable{

    Account a;

    int amt;public static void main(String str[]){

    Account lb= new Account(1000);

    new ThreadTest(lb,"A",500);

    new ThreadTest(lb,"B",750);}

    public ThreadTest(Account a,String name,int

    amt){this.a=a;

    this.amt=amt;

    new Thread(this,name).start();}

    Folder 7

  • 8/14/2019 8 Threads

    44/74

    44Java

    public void run(){ a.withdraw(amt);}}

    class Account{

    private int money;

    Account(int amt){ money=amt;}

    void deposit(int amt){

    try{

    // doing io operation

    Thread.sleep(1000); }

    catch(Exception e){}

    money=money+amt;

    System.out.println("Balance "+ money);}

  • 8/14/2019 8 Threads

    45/74

    45Java

    void withdraw(int amt){

    if(amt

  • 8/14/2019 8 Threads

    46/74

    46Java

    System.out.println("Sorry "+Thread.currentThread().getName()+ "Requested

    amt ("+ amt +") is not available.");

    System.out.println("Balance "+ money);

    }

    }

    Result:

    Received 500 by A

    Balance 500

    Received 750 by B

    Balance -250

  • 8/14/2019 8 Threads

    47/74

    47Java

    Solution to the Account problem

    Account

    money:

    Rs.1000

    Rs 500

    Thread A locks the object and calls withdraw(500)

    Thread A waits for the transaction to complete

    Thread A updates the money to (1000-

    500)=500 and releases the lock.

    Thread B waits for A to release the lock

    Account

    money:

    Rs.500Thread B gets the message that it cannot withdrawthe requested amount

    Thread B locks the object and calls withdraw(750)

    Thread B releases the lock.

  • 8/14/2019 8 Threads

    48/74

    48Java

    Locking

    In java, the object gets locked in two situations: When a thread calls a synchronized method of an

    object. In this case, lock is released as soon as

    the method finishes its execution. No other thread

    can access any synchronized methods of that

    object, till the lock on the object is released.

    synchronized void deposit(int amt)

  • 8/14/2019 8 Threads

    49/74

    49Java

    B.When an object is explicitly locked by thestatement

    synchronized(object){ }

    In such cases, all the methods of the objectremain locked until the block of statementwithin synchronized block finishes execution.

  • 8/14/2019 8 Threads

    50/74

    50Java

    Synchronized Code

    Solution using approach A:Add synchronized keyword to deposit and withdrawmethods of the Account class, compile and execute.

    synchronized void deposit(int amt) synchronized

    void withdraw(int amt)Solution using approach B:

    Change the run method of ThreadTest class to

    public void run(){

    synchronized(a){

    a.withdraw(amt); } }Folder 8

  • 8/14/2019 8 Threads

    51/74

    51Java

    Result :

    Received 500 by A

    Balance 500

    Sorry B Requested amt (750) is

    not available.

    Balance 500

  • 8/14/2019 8 Threads

    52/74

    52Java

    So what about staticmethods? Can they besynchronized?

    Yes you can synchronizestatic methods to protect

    static data. But what happens

    is that the Class objectof the

    corresponding object gets

    locked !

    A few more points !

  • 8/14/2019 8 Threads

    53/74

    53Java

    A few more points !

    synchronized methods of super class can be

    overridden to be unsynchronized. Constructors cannot be declared as synchronized. A non-static inner class can lock its containing

    class using a synchronized block.

    Methods in the interface cannot be declared assynchronized.

    The locking does not prevent threads fromaccessing unsynchronized methods.

    Synchronized methods are also called thread-safemethods.

  • 8/14/2019 8 Threads

    54/74

    54Java

    Do you recall I told you StringBuffer

    is thread-safe. Using StringBuffer

    doesnt allow you to take fulladvantage of the multithreading. So,

    if you are sure that your threads can

    simultaneously call methods of same

    string without causing unnecessary

    side effects use StringBuilder.

  • 8/14/2019 8 Threads

    55/74

    55Java

    Deadlocks

    Your turn now.. Can you

    explain a situation when

    deadlocks can occur ?

    And in lab, try to write somejava code that creates a

    deadlock. Of course, this

    should also be your last time to

    write such code!

    I t th d i ti

  • 8/14/2019 8 Threads

    56/74

    56Java

    Inter-thread communication Inter-thread communication is required when

    execution of one thread depends on another thread.In such case, the second thread intimates ornotifies the first thread when it has finished what thefirst thread is waiting for.

    The best suited situation to understand this is aproducer-consumer problem.

    Producer

    consumer

    Methods of Object class used for

  • 8/14/2019 8 Threads

    57/74

    57Java

    Methods of Object class used for

    thread communication

    final void wait() throws InterruptedExceptionfinal void wait(long timeout) throwsInterruptedException

    The above methods causes current thread to wait until eitheranother thread invokes the notify() method or the notifyAll()method for this object, or a specified amount of time haselapsed.

    final void notify(): Wakes up a single thread that is

    waiting on this object's lock.final void notifyAll(): Wakes up all threads that arewaiting on this object's lock.

  • 8/14/2019 8 Threads

    58/74

    58Java

    wait() and notify()

    Both of these methods must be called from asynchronized context. If this is not done

    IllegalMonitorStateException is thrown atruntime.

    When a thread calls wait() method, it relinquishesthe lock on the object (unlike sleep method).

    When a thread calls notify() method, the lock is not

    released. Another word frequently used for lock is monitor.

  • 8/14/2019 8 Threads

    59/74

    59Java

    public class ProducerConsumer implementsRunnable{

    int apples;

    public static void main(String s[]){

    ProducerConsumer pc = new ProducerConsumer();

    Thread producer= new Thread(pc, "Tree");

    Thread consumer1= new Thread(pc, "Earthworm");

    Thread consumer2= new Thread(pc, "Man");

    producer.start();

    consumer1.start();

    consumer2.start();}

    h i d id d (){

  • 8/14/2019 8 Threads

    60/74

    60Java

    synchronized void produce(){

    while(true){

    if(apples>100)

    try{

    System.out.println("Waiting for apples to be

    eaten");wait(); }catch(InterruptedException e){}

    try{

    int i=(int)(Math.random()*500);Thread.sleep(i);

    apples=apples+i;

    Produce apples only if thereare

  • 8/14/2019 8 Threads

    61/74

    61Java

    System.out.println( Produced apples = + apples);

    }catch(InterruptedException e){}

    notifyAll(); } }

    synchronized void consume(){

    while(true){int i=(int)(Math.random()*1000);

    if(apples

  • 8/14/2019 8 Threads

    62/74

    62Java

    try{

    System.out.println(Thread.currentThread().getNam()+ " busy eating "+ i/10 +" apples");

    Thread.sleep(i);

    apples=apples-i/10; }

    catch(InterruptedException e){}notify(); } }

    public void run(){

    if(Thread.currentThread().getName().equals("Tree"))

    produce();

    else consume(); }}

    Simulating time taken to eatapples.

  • 8/14/2019 8 Threads

    63/74

    63Java

    Produced apples =111

    Waiting for apples to be eaten

    Earthworm busy eating 86 apples

    Earthworm waiting for more apples

    Man busy eating 8 apples

    Man busy eating 5 apples

    Man waiting for more apples

    Produced apples =124

    Waiting for apples to be eaten

    Earthworm busy eating 85 apples

    Earthworm busy eating 20 apples

    Sample result

    Daemon threads

  • 8/14/2019 8 Threads

    64/74

    64Java

    Daemon threads

    A program continues to execute as long as it hasat least one (non-daemon) thread that is alive.

    The threads we have seen so far are non-daemon.

    Daemon threads are the threads which cease toexecute when there are no non-daemon threadsalive.

    Example: garbage collector thread.

    final void setDaemon(boolean on)boolean isDaemon()

  • 8/14/2019 8 Threads

    65/74

    65Java

    Go through the code given

    in the next slide carefully.

    Try and answer the

    question listed below the

    code. You can take 24

    hours to think !

    Challenge your mind

    class A extends Thread {

  • 8/14/2019 8 Threads

    66/74

    66Java

    class A extends Thread {String sa;public A(String sa) {this.sa = sa;}public void run() {synchronized (sa) {while(!sa.equals("Done")){

    try{sa.wait();}catch(Exception e){}}}

    System.out.println(sa);}}

  • 8/14/2019 8 Threads

    67/74

    67Java

    class B {private static String sa = new

    String("Not Done");public static void main (String[]args) {

    synchronized (sa) {

    Thread t1 = new A(sa);t1.start();sa="Done";sa.notify();

    }}}

    On executing the above code, it throwsIllegalMonitorStateException . Why?

  • 8/14/2019 8 Threads

    68/74

    68

    Java

    Thread Groups

    Thread groups are collection of threads into one object . This helps in manipulating a collection of threads all at a

    time instead of manipulating each of them individually .

    For instance all the threads in a collection can be started

    together. Every Java thread is a member of some thread group.

    When a thread is created, unless it is explicitly put in athread group, the runtime system automatically placesthe new thread in the same group as the thread that

    created it. When a Java application first starts up, the Java runtime

    system creates a ThreadGroup named "main".

  • 8/14/2019 8 Threads

    69/74

    69

    Java

    Creating the ThreadGroup

    ThreadGroup(String name)

    ThreadGroup(ThreadGroup parent,

    String name)

    final ThreadGroup getThreadGroup()

    Is a method of Thread class that returns the

    thread group the calling thread belongs to.

  • 8/14/2019 8 Threads

    70/74

    70

    Java

    Methods of a ThreadGroup

    Methods to enumerate: int enumerate(Thread[] list)

    int enumerate(Thread[] list,

    boolean recurse) Methods with respect to the group

    int activeCount()

    ThreadGroup getParent() String getName()

    boolean parentOf(ThreadGroup g)

    class EnumeratedThreads {

  • 8/14/2019 8 Threads

    71/74

    71

    Java

    public static void main(String s[]) {ThreadGroup currentGroup =

    Thread.currentThread().getThreadGroup();int no;Thread listOfThreads[];no = currentGroup.activeCount();

    listOfThreads = new Thread[no];

    currentGroup.enumerate(listOfThreads);for (int i = 0; i < no; i++) {

    System.out.println("Thread #" +i + " = " + listOfThreads[i].getName());

    }

    }}

    Methods to with respect to the

  • 8/14/2019 8 Threads

    72/74

    72

    Java

    Methods to with respect to the

    threads as a group

    int getMaxPriority()

    void setMaxPriority(int pri)

    void interrupt()

    void destroy()boolean isDaemon()

    void setDaemon(boolean daemon )

    void list()

    class ThreadGroupDemo{

  • 8/14/2019 8 Threads

    73/74

    73

    Java

    class ThreadGroupDemo{public static void main (String [] args){ThreadGroup tg = new ThreadGroup ("group

    1");Thread t1 = new Thread (tg, "thread 1");Thread t2 = new Thread (tg, "thread 2");Thread t3 = new Thread (tg, "thread 3");

    tg = new ThreadGroup ("group 2");Thread t4 = new Thread (tg, "thread 4");

    tg = Thread.currentThread().getThreadGroup ();

  • 8/14/2019 8 Threads

    74/74

    int agc = tg.activeGroupCount ();System.out.println ("Active thread

    groups in " + tg.getName () +" threadgroup: " + agc);

    tg.list ();}

    }

    Active thread groups in main thread group: 2

    java.lang.ThreadGroup[name=main,maxpri=10]Thread[main,5,main]

    java.lang.ThreadGroup[name=group 1,maxpri=10]

    java.lang.ThreadGroup[name=group 2,maxpri=10]