thread in java

Embed Size (px)

Citation preview

  • 7/29/2019 thread in java

    1/56

    A thread can be loosely defined as a separatestream of execution that takes place simultaneouslywith and independently of everything else that might

    be happening.

    A thread is like a classic program that starts atpoint A and executes until it reaches point B. It does

    not have an event loop

    A thread runs independently of anything elsehappening in the computer.

  • 7/29/2019 thread in java

    2/56

    1- Java applications and applets are naturallythreaded. The runtime environment starts execution ofthe program with the main() method in one thread

    2- Garbage collection takes place in another thread.Screen updating occurs in a third thread. There may beother threads running as well, mostly related to thebehavior of the virtual machine.

    3- All of this happens invisibly to the programmer.Some of the time you're only concerned with whathappens in the primary thread which includes themain() method of a program. If this is the case you may

    not need to worry about threading at all.

  • 7/29/2019 thread in java

    3/56

    Java has two ways a program can implementthreading. One is to create a subclass ofjava.lang.Thread. However sometimes you'll want to

    thread an object that's already a subclass of anotherclass. Then you use the java.lang.Runnable interface.

    The Thread class has three primary methods that areused to control a thread:

    public void start()public void run()

    public final void stop()

  • 7/29/2019 thread in java

    4/56

    The start() method prepares a thread to be run; therun() method actually performs the work of the thread;and the stop() method halts the thread.

    The thread dies when the run() method terminates orwhen the thread's stop() method is invoked.

    You never call run() explicitly. It is called

    automatically by the runtime as necessary once you'vecalled start().

  • 7/29/2019 thread in java

    5/56

    The following program is a thread that prints the numbersbetween -128 and 127.

    public class BytePrinter extends Thread

    { public void run() {

    for (int b = -128; b < 128; b++) { System.out.println(b); } } }

    public class ThreadTest {public static void main(String[] args) {System.out.println("Constructing the thread...");BytePrinter bp = new BytePrinter();System.out.println("Starting the thread...");

    bp.start();

    System.out.println("The thread has been started.");System.out.println("The main() method is finishing.");return; } }

  • 7/29/2019 thread in java

    6/56

    class SimpleThread extends Thread

    { public SimpleThread(String str)

    { super(str);

    }

    public void run()

    { for (int i = 0; i < 10; i++)

    { System.out.println(i + " " + getName());try { sleep((int)(Math.random() * 1000));

    } catch (InterruptedException e) {} }System.out.println("DONE! " + getName()); } }

    class TwoThreadsTest {public static void main (String[] args) {

    new SimpleThread("Jamaica").start();

    new SimpleThread("Fiji").start(); } }

  • 7/29/2019 thread in java

    7/56

    A thread is not an object, it's a series of executedinstructions zipping thru method calls. Imaginemultiple CPUs and each one running code in yourprogram (same data space) at the same time like antscrawling all over a code printout. Java and theoperating system take care of making one or a fewCPUs handle many threads.

    Advantage:

    --support concurrent operation. HTTP server.crontab system (restarts managers, does stats, etc...).

    ---better system response. Add forum message; mustadd to search engine, email monitors. exploitparallelism. dual server: supports simultaneousexecution

  • 7/29/2019 thread in java

    8/56

    Extend thejava.lang.Thread Class.Override the run( ) method in the subclass from the Thread classto define the code executed by the thread.Create an instance of this subclass.This subclass may call a Thread class constructor by subclassconstructor.Invoke the start( ) method on the instance of the class to makethe thread eligible for running.

  • 7/29/2019 thread in java

    9/56

    The following program demonstrates a single threadcreation extending the "Thread" Class:

    class MyThread extends Thread{

    String s=null;MyThread(String s1)

    {s=s1;start();

    }public void run(){

    System.out.println(s);}

    }

    public class RunThread{public static void main(String args[]){

    MyThread m1=new MyThread("Thread started....");}

    }

  • 7/29/2019 thread in java

    10/56

    II. Implementing the java.lang.Runnable InterfaceThe procedure for creating threads by implementing the Runnable Interface is as follows:

    A Class implements the Runnable Interface, override the run() method to define thecode executed by thread. An object of this class is Runnable Object.Create an object ofThread Class by passing a Runnable object as argument.

    Invoke the start( ) method on the instance of the Thread class.The following program demonstrates the thread creation implenting theRunnable interface:

    class MyThread1 implements Runnable{

    Thread t;String s=null; MyThread1(String s1){s=s1;t=new Thread(this);t.start();

    }public void run(){

    System.out.println(s);

    }}public class RunableThread{

    public static void main(String args[]){MyThread1 m1=new MyThread1("Thread started....");}

    }

  • 7/29/2019 thread in java

    11/56

    Several constructors are available for creating newThread instances.

    Thread()

    Thread(String)

    Thread(Runnable)Thread(Runnable,String)

    Thread(ThreadGroup,String)

    Thread(ThreadGroup,Runnable)Thread(ThreadGroup,Runnable,String)

    Thread(ThreadGroup, Runnable, String, long)

  • 7/29/2019 thread in java

    12/56

    ThreadGroupAll threads belongs to an instance ofthe ThreadGroup Class.

    -- ThreadGroup is used to represent a group ofthreads.

    --ThreadGroups can be shown in a hierarchicalmanner.

    -- There is only one root ThreadGroup that containsall other thread and groups and each subgroups cancontain other groups and threads.

    If a thread x in group1, and executes the code:

    ThreadGroup group2=newThreadGroup(group2);

  • 7/29/2019 thread in java

    13/56

    Then the newly formed group2 comes under group1. If youwant a parent group other than default then you have to

    specify the parent group at the time of creation.

    ThreadGroup group2=newThreadGroup(group2,group3);

    Then newly formed group3 comes under the group2.

    Some important methods are:

    getName()This method is used to retrieve the name ofparticular group.ThreadGroup g=new ThreadGroup(Hello);String gname=g.getName();

    getParent() This method is used to retrieve the name ofparent threadgroup of sub group.

    ThreadGroup group=group3.getParent();

  • 7/29/2019 thread in java

    14/56

    Multitasking :

    Multitasking allow to execute more than one tasks

    at the same time, a task being a program. Inmultitasking only one CPU is involved but it canswitches from one program to another program soquickly that's why it gives the appearance of executing

    all of the programs at the same time.

    Multitasking allow processes (i.e. programs) to runconcurrently on the program. For Example running thespreadsheet program and you are working with wordprocessor also.Multitasking is running heavyweight processes by asingle OS.

  • 7/29/2019 thread in java

    15/56

    Multithreading :

    Multithreading is a technique that allows a program or aprocess to execute many tasks concurrently (at the same

    time and parallel). It allows a process to run its tasks inparallel mode on a single processor system

    In the multithreading concept, several multiple

    lightweight processes are run in a single process/task orprogram by a single processor. For Example, When you useaword processor you perform a many different tasks suchas printing, spell checking and so on. Multithreaded

    software treats each process as a separate program.

  • 7/29/2019 thread in java

    16/56

    For example, look at the diagram shown as:

    In this diagram, two threads are being executed having morethan one task. The task of each thread is switched to the task ofanother thread.

    Advantages of multithreading over multitasking :

    Reduces the computation time.

    Improves performance of an application.Threads share the same address space so it saves the memory.

    Context switching between threads is usually less expensive thanbetween processes.

    Cost of communication between threads is relatively low.

  • 7/29/2019 thread in java

    17/56

    Different states implementing Multiple-Threadsare:

    As we have seen different states that may beoccur with the single thread. A running thread canenter to any non-runnable state, depending on thecircumstances. A thread cannot enters directly to therunning state from non-runnable state, firstly it goes torunnable state.

  • 7/29/2019 thread in java

    18/56

    Now lets understand the some non-runnable stateswhich may be occur handling the multithreads.

    SleepingOn this state, the thread is still alive but it is

    not runnable, it might be return to runnable state later, if aparticular event occurs. On this state a thread sleeps for aspecified amount of time. You can use the method sleep( )to stop the running state of a thread.

    static void sleep(long millisecond) throwsInterruptedException

    Waiting for NotificationA thread waits for notificationfrom another thread. The thread sends back to runnablestate after sending notification from another thread.

  • 7/29/2019 thread in java

    19/56

    Blocked on I/O The thread waits for completionof blocking operation. A thread can enter on this statebecause of waiting I/O resource. In that case the

    thread sends back to runnable state after availability ofresources.

    Blocked for joint completion The thread cancome on this state because of waiting the completionof another thread.

  • 7/29/2019 thread in java

    20/56

    Lets see an example having the implementation of the multithreads byextending Thread Class:

    class MyThread extends Thread{MyThread(String s){

    super(s);start();

    }public void run(){

    for(int i=0;i

  • 7/29/2019 thread in java

    21/56

    Output of the Program

    C:\java>javac MultiThread1.javaC:\java>java MultiThread1Thread Name :mainThread Name :My Thread 1Thread Name :My Thread 2Thread Name :My Thread 1Thread Name :My Thread 2Thread Name :My Thread 1Thread Name :My Thread 2Thread Name :My Thread 1Thread Name :My Thread 2Thread Name :My Thread 1Thread Name :My Thread 2

  • 7/29/2019 thread in java

    22/56

    Now, lets create the same program implenting the Runnable interface:

    class MyThread1 implements Runnable{Thread t;MyThread1(String s) {

    t=new Thread(this,s);t.start();

    }

    public void run() {for(int i=0;i

  • 7/29/2019 thread in java

    23/56

    Thread Priorities

    In Java, thread scheduler can use the thread prioritiesin the form ofinteger value to each of its thread to

    determine the execution schedule of threads .

    Thread gets the ready-to-run state according to theirpriorities. The thread scheduler provides the CPU

    time to thread of highest priority during ready-to-runstate.

    Priorities are integer values from 1 (lowest prioritygiven by the constant Thread.MIN_PRIORITY) to 10

    (highest priority given by the constantThread.MAX_PRIORITY).

    The default priority is 5(Thread.NORM_PRIORITY).

  • 7/29/2019 thread in java

    24/56

    Thread Priorities

    Constant Description

    Thread.MIN_PRIORITY The maximum priority of anythread (an int value of 10)

    Thread.MAX_PRIORITY The minimum priority of anythread (an int value of 1)

    Thread.NORM_PRIORITY The normal priority of any

    thread (an int value of 5)

  • 7/29/2019 thread in java

    25/56

    Thread Priorities

    Method DescriptionsetPriority() This is method is used to set

    the priority of thread.

    getPriority() This method is used to getthe priority of thread

  • 7/29/2019 thread in java

    26/56

    Thread Scheduler

    In the implementation of threading scheduler usuallyapplies one of the two following strategies:

    Preemptive schedulingIf the new thread has ahigher priority then current running thread leaves therunnable state and higher priority thread enter to therunnable state.

    Time-Sliced (Round-Robin) SchedulingArunning thread is allowed to be execute for the fixedtime, after completion the time, current threadindicates to the another thread to enter it in therunnable state.

    You can also set a thread's priority at any time afterits creation using the setPrioritymethod. Lets see,how to set and get the priority of a thread.

  • 7/29/2019 thread in java

    27/56

    class MyThread1 extends Thread{MyThread1(String s){

    super(s);start();

    }public void run(){

    for(int i=0;i

  • 7/29/2019 thread in java

    28/56

    Output of the Program:

    C:\java>javac ThreadPriority.java

    C:\java>java ThreadPriority

    Thread Name :My Thread 1Thread Name :My Thread 2Thread Priority :Thread[My Thread 2,10,main]Thread Name :My Thread 2Thread Priority :Thread[My Thread 2,10,main]Thread Name :My Thread 2Thread Priority :Thread[My Thread 2,10,main]

    Thread Priority :Thread[My Thread 1,1,main]Thread Name :My Thread 1Thread Priority :Thread[My Thread 1,1,main]Thread Name :My Thread 1Thread Priority :Thread[My Thread 1,1,main]

    In this program two threads are created. We have set up maximum priority

    for the second thread "MyThread2" and minimum priority for the first thread"MyThread1" i.e. the after executing the program, the first thread is executedonly once and the second thread "MyThread2" started to run until either it getsend or another thread of the equal priority gets ready to run state.

  • 7/29/2019 thread in java

    29/56

    Deadlock

    A situation where a thread is waiting for an objectlock that holds by second thread, and this secondthread is waiting for an object lock that holds by firstthread, this situation is known as Deadlock.

    Lets see a situation in the diagram shown below

    where the deadlock condition is occurred :

  • 7/29/2019 thread in java

    30/56

    Deadlock

    In this diagram two threads having the Printing & I/Ooperations respectively at a time. But Thread1 need to

    printer that is hold up by the Thread2, likewise Thread2need the keyboard that is hold up by the Thread1. In thissituation the CPU becomes ideal and the deadlockcondition occurs because no one thread is executed untilthe hold up resources are free.

  • 7/29/2019 thread in java

    31/56

    Deadlock

    The following program demonstrates the deadlock situation:public class DeadDemo{

    public static void main(String args[]){

    String s1="Dead";String s2="Lock";MyThread1 m=new MyThread1(s1,s2);MyThread2 m1=new MyThread2(s1,s2);}

    }

    class MyThread1 extends Thread{String s1;String s2;MyThread1(String s1, String s2){this.s1=s1;this.s2=s2;start();}

  • 7/29/2019 thread in java

    32/56

    Public void run(){while(true){synchronized(s1){

    synchronized(s2){

    System.out.println(s1+s2);}}}

    }}class MyThread2 extends Thread{

    String s1;String s2;MyThread2(String s1,String s2){

    this.s1=s1;this.s2=s2;start();

    }

  • 7/29/2019 thread in java

    33/56

    public void run(){while(true){

    synchronized(s2){

    synchronized(s1){System.out.println(s2+s1);

    }}}

    }}

  • 7/29/2019 thread in java

    34/56

    Output of the program is:C:\j2se6\thread>javac DeadDemo.java

    C:\j2se6\thread>java DeadDemoDeadLockDeadLockDeadLockDeadLockDeadLockDeadLockDeadLockDeadLockLockDeadLockDeadLockDead

    LockDeadLockDeadLockDeadLockDeadDeadLockDeadLockDeadLockDeadLockDeadLockDeadLockDeadLock..................C:\j2se6\thread>

  • 7/29/2019 thread in java

    35/56

    Synchronized Threads:

    In Java, the threads are executed independently toeach other. These types of threads are called asasynchronous threads. But there are two problemsmay be occur with asynchronousthreads.

    Two or more threads share the same resource(variable or method) while only one of them can accessthe resource at one time.

    If the producer and the consumer are sharing thesame kind of data in a program then either producermay produce the data faster or consumer may retrievean order of data and process it without its existing.

  • 7/29/2019 thread in java

    36/56

    Synchronized Threads:

    Suppose, we have created two methods as increment() and decrement( ). which increases or decreasesvalue of the variable "count" by 1 respectively shownas:

    public void increment( ) {count++;

    }

    public void decrement( ) {count--;

    } public int value() {

    return count; }

  • 7/29/2019 thread in java

    37/56

    Synchronized Threads:

    When the two threads are executed to access thesemethods (one for increment( ),another fordecrement( )) then both will share the variable"count". in that case, we can't be sure that what valuewill be returned of variable "count".We can see this problem in the diagram shown below:

  • 7/29/2019 thread in java

    38/56

    Synchronized Threads:

    To avoid this problem, Java uses monitor alsoknown as semaphore to prevent data from being

    corrupted by multiple threads by a keywordsynchronized to synchronize them andintercommunicate to each other. It is basically amechanism which allows two or more threads to shareall the available resources in a sequential manner.

    Java's synchronized is used to ensure that only onethread is in a critical region. critical region is a lockarea where only one thread is run (or lock) at a time.Once the thread is in its critical section, no other

    thread can enter to that critical region. In that case,another thread will has to wait until the current threadleaves its critical section.

  • 7/29/2019 thread in java

    39/56

    Synchronized Threads:

    General form of the synchronized statement is as:

    synchronized(object) {

    // statements to be synchronized

    }Lock:

    Lock term refers to the access granted to a particular

    thread that can access the shared resources. At any giventime, only one thread can hold the lock and thereby haveaccess to the shared resource. Every object in Java has build-in lock that only comes in action when the object hassynchronized method code. By associating a sharedresource with a Java object and its lock, the object can act asa guard, ensuring synchronized access to the resource. Onlyone thread at a time can access the shared resource guardedby the object lock.

  • 7/29/2019 thread in java

    40/56

    Synchronized Threads:

    Since there is one lock per object, if one thread hasacquired the lock, no other thread can acquire the lockuntil the lock is not released by first thread. Acquirethe lock means the thread currently in synchronizedmethod and released the lock means exits thesynchronized method.

    Remember the following points related to lock andsynchronization:

    Only methods (or blocks) can be synchronized,Classes and variable cannot be synchronized.

    All methods in a class need not to be synchronized.A class can have both synchronized and non-synchronized methods.

  • 7/29/2019 thread in java

    41/56

    Synchronized Threads:

    There are two ways to synchronized the executionof code:

    1-Synchronized Methods2-Synchronized Blocks (Statements)

    Synchronized Methods:Any method is specified with the keyword

    synchronized is only executed by one thread at atime. If any thread want to execute the synchronized

    method, firstly it has to obtain the objects lock. If thelock is already held by another thread, then callingthread has to wait.

  • 7/29/2019 thread in java

    42/56

    Synchronized Threads:

    Synchronized methods are useful in thosesituations where methods are executed concurrently, sothat these can be intercommunicate manipulate thestate of an object in ways that can corrupt the state if .Stack implementations usually define the twooperations push and pop of elements as synchronized,thats why pushing and popping are mutually exclusiveoperations.

    For Example if several threads were sharing a stack,if one thread is popping the element on the stack thenanother thread would not be able to pushing theelement on the stack.

    h d h d

  • 7/29/2019 thread in java

    43/56

    Synchronized Threads:

    class Share extends Thread{static String msg[]={"This", "is", "a", "synchronized", "variable"};Share(String threadname){

    super(threadname);}public void run(){display(getName());

    }public synchronized void display(String threadN){

    for(int i=0;i

  • 7/29/2019 thread in java

    44/56

    Synchronized Threads:

    Output of the program is:

    C:\java>javac SynThread.java

    C:\java>java SynThreadThread One: ThisThread One: isThread One: aThread One: synchronizedThread One: variableThread Two: ThisThread Two: isThread two: aThread Two: synchronized

    Thread Two: variableIn this program, the method "display( )" is synchronized that

    will be shared by both thread's objects at the time of programexecution. Thus only one thread can access that method andprocess it until all statements of the method are executed.

  • 7/29/2019 thread in java

    45/56

    Synchronized Threads:

    Synchronized Blocks (Statements)

    Another way of handling synchronization is

    Synchronized Blocks (Statements). Synchronizedstatements must specify the object that provides thenative lock. The synchronized block allows executionof arbitrary code to be synchronized on the lock of an

    arbitrary object.

    General form of synchronized block is:

    synchronized (object reference expression)

    {// statements to be synchronized}

    S h i d Th d

  • 7/29/2019 thread in java

    46/56

    Synchronized Threads:

    class Share extends Thread{static String msg[]={"This", "is", "a", "synchronized", "variable"};Share(String threadname){

    super(threadname);}public void run(){display(getName());

    }public void display(String threadN){

    synchronized(this){

    for(int i=0;i

  • 7/29/2019 thread in java

    47/56

  • 7/29/2019 thread in java

    48/56

    Inter-Thread Communication:

    Java provides a very efficient way through whichmultiple-threads can communicate with each-other.This way reduces the CPUs idle time i.e. A processwhere, a thread is paused running in its critical regionand another thread is allowed to enter (or lock) in thesame critical section to be executed. This technique is

    known as Interthread communication which isimplemented by some methods. These methods aredefined in "java.lang" package and can only becalled within synchronized code shown as:

  • 7/29/2019 thread in java

    49/56

    Inter-Thread Communication:

    Method Descriptionwait( ) It indicates the calling thread to give

    up the monitor and go to sleep untilsome other thread enters the samemonitor and calls method notify() ornotifyAll().

    notify( ) It wakes up the first thread that calledwait() on the same object.

    notifyAll( ) Wakes up (Unloack) all the threadsthat calledwait( ) on the same object.The highest priority thread will run

    first.

    class Shared {

  • 7/29/2019 thread in java

    50/56

    class Shared {

    int num=0;booleanvalue = false;

    synchronized int get() {if(value==false)

    try{wait();}

    catch (InterruptedException e) {System.out.println("InterruptedException caught");}

    System.out.println("consume: " + num);value=false;notify();return num;

    }

    synchronized void put(int num) {if(value==true)try{wait();}

    catch (InterruptedException e) {System.out.println("InterruptedException caught");

    }this.num=num;System.out.println("Produce: " + num);

    value=false;notify();}}

    class Producer extends Thread {

  • 7/29/2019 thread in java

    51/56

    class Producer extends Thread {Shared s;

    Producer(Shared s) {this.s=s;this.start();

    }

    public void run() {int i=0;

    s.put(++i);}

    }

    class Consumer extends Thread{Shared s;

    Consumer(Shared s) {this.s=s;this.start();

    }

    public void run() {s.get();}

    }

    public class InterThread{public static void main(String[] args){Shared s=new Shared();new Producer(s);new Consumer(s);

    }}

    O f h P

  • 7/29/2019 thread in java

    52/56

    Output of the Program:

    C:\java>javac InterThread.java

    C:\java>java InterThreadProduce: 1consume: 1

    In this program, two threads "Producer" and"Consumer" share the synchronized methods of the class"Shared". At time of program execution, the "put( )"method is invoked through the "Producer" class which

    increments the variable "num" by1. After producing 1 bythe producer, the method "get( )" is invoked by through the"Consumer" class which retrieves the produced numberand returns it to the output. Thus the Consumer can'tretrieve the number without producing of it.

    Another program demonstrates the uses of wait() &

  • 7/29/2019 thread in java

    53/56

    Another program demonstrates the uses of wait() &notify() methods:

    public class DemoWait extends Thread{intval=20;public static void main(String args[]) {

    DemoWait d=new DemoWait();d.start();new Demo1(d);

    }public void run(){try {synchronized(this){

    wait();System.out.println("value is :"+val);}}catch(Exception e){}

    }

  • 7/29/2019 thread in java

    54/56

    public voidvalchange(intval){

    this.val=val;try {synchronized(this) {

    notifyAll();}}catch(Exception e){}

    }}class Demo1 extends Thread{DemoWait d;Demo1(DemoWait d) {this.d=d;start();}public void run(){

    try{System.out.println("Demo1 value is"+d.val);d.valchange(40);

    }catch(Exception e){}}

    }

  • 7/29/2019 thread in java

    55/56

    Output of the program is:

    C:\j2se6\thread>javac DemoWait.java

    C:\j2se6\thread>java DemoWaitDemo1 value is20value is :40

    C:\j2se6\thread>

  • 7/29/2019 thread in java

    56/56