multithreading and synchronization

Upload: ricketbus

Post on 02-Jun-2018

227 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/10/2019 MultiThreading and Synchronization

    1/43

    Multithreaded Programming

    Java provides built-in support for multithreaded

    programming. A multithreaded program contains two or

    more parts that can run concurrently. Each part of such a

    program is called a thread and each thread defines aseparate path of execution. Thus multithreading is a

    specialized form of multitasking.

    Two types of multitasking:

    Process based

    Thread based.

  • 8/10/2019 MultiThreading and Synchronization

    2/43

    Multithreaded Programming

    A process is a program that is executing. Thus process-

    based multitasking is the feature that allows your

    computer to run two or more programs concurrently.

    Example process based multitasking enables you to runthe java compiler at the same time that you are using a

    text editor. In process based multitasking, a program is

    the smallest unit of code.

  • 8/10/2019 MultiThreading and Synchronization

    3/43

  • 8/10/2019 MultiThreading and Synchronization

    4/43

    Process versus thread based

    multitasking

    Threads are lightweight. They share same address space.

    Inter thread communication is inexpensive, and context

    switching from one thread to the next is low cost.

    Process-based multitasking is not under the control ofJava but multithreaded multitasking is in control.

  • 8/10/2019 MultiThreading and Synchronization

    5/43

    Java Thread Model

    Single threaded systems use an approach called an event loop

    with polling. In this model a single thread of control runs in an

    infinite loop, polling a single event queue to decide what to do

    next. Sometimes this method wastes CPU time or entireprogram stops running.

    Javasmultithreading is that the main loop/polling mechanism

    is eliminated. One thread can pause without stopping other

    parts of your program. When thread blocks Java program, only

    the single thread that is blocked pauses. All other threads

    continue to run.

  • 8/10/2019 MultiThreading and Synchronization

    6/43

    Thread states

    Threads exist in several states.

    Running

    Ready

    Suspended

    Resumed

    Blocked

    terminated

  • 8/10/2019 MultiThreading and Synchronization

    7/43

    synchronization

    Multithreading introduces an asynchronous behavior so you must

    prevent one thread from writing data while another thread is in the

    middle of reading it.

    Java implements interprocess synchronization called monitor.

    Monitor a very small box that can hold only one thread. Once a

    thread enters a monitor, all other threads must wait until that thread

    exits the monitor.

    There is no class Monitor,instead each object has its own implicit

    monitor that is automatically entered when one of the objectssynchronized methods is called. Once a thread is inside a

    synchronized method, no other thread can call any other

    synchronized method on the same object.

  • 8/10/2019 MultiThreading and Synchronization

    8/43

    Messaging

    Java provides a clean, low cost way for two or more threads to

    communicate with each other via calls to predefined methods

    that all object have.

    Javas messaging system allows a thread to enter asynchronized method on an object, and then wait there until

    some other thread explicitly notifies it to come out.

  • 8/10/2019 MultiThreading and Synchronization

    9/43

    The Thread Class and the Runnable

    Interface

    Javas multithreading system is built upon the thread class, its methods, and its

    companion interface, Runnable.

    To create a new thread, your program will either extend Thread or implement the

    Runnable interface.

    The thread class defines several methods that help to manage threads.

    Method Meaning

    getName Obtain a threads name.

    getPriority Obtain a threads priority.

    isAlive Determine if a thread is still running.Join Wait for a thread to terminate.

    Run Entry point for the thread.

    Sleep Suspend a thread for a period of time.

    Start Start a thread by calling its run method.

  • 8/10/2019 MultiThreading and Synchronization

    10/43

    Extending Thread class

    We can make our class runnable as a thread by extending the

    class java.lang.Thread. This gives us access to all the thread

    methods directly.

    Steps Declare the class as extending the Thread class

    Implement the run() method that is responsible for

    executing the sequence of code that the thread will execute.

    Create a thread object and call the start() method to initiatethe thread execution.

  • 8/10/2019 MultiThreading and Synchronization

    11/43

    Declaring the class

    The thread class can be extended as follows:

    Class Mythread extends Thread

    {---------

    ---------

    }

  • 8/10/2019 MultiThreading and Synchronization

    12/43

  • 8/10/2019 MultiThreading and Synchronization

    13/43

    Starting new thread

    To actually create and run an instance of our thread class.

    Mythread athread= new Mythread();// creates object

    athread.start();

  • 8/10/2019 MultiThreading and Synchronization

    14/43

    class A extends Thread

    {

    public void run()

    {

    for(int i=1;i

  • 8/10/2019 MultiThreading and Synchronization

    15/43

    Class B extends Thread

    {

    public void run(){

    for(int j=1;j

  • 8/10/2019 MultiThreading and Synchronization

    16/43

    Class C extends Thread

    {

    public void run()

    {for(int k=1;k

  • 8/10/2019 MultiThreading and Synchronization

    17/43

    class Threadtest

    {public static void main(String args[])

    {

    new A() .start();new B().start();

    new C().start();

    }

    }

  • 8/10/2019 MultiThreading and Synchronization

    18/43

    class A extends Thread

    {public void run()

    {

    for(int i=1;i

  • 8/10/2019 MultiThreading and Synchronization

    19/43

    class B extends Thread

    {

    public void run(){

    for(int j=1;j

  • 8/10/2019 MultiThreading and Synchronization

    20/43

    class C extends Thread

    {

    public void run()

    {

    for(int k=1;k

  • 8/10/2019 MultiThreading and Synchronization

    21/43

    class ThreadMethods

    {

    public static void main(String args[])

    {A threadA=new A();

    B threadB=new B();

    C threadC=new C();

    System.out.println("start thread A");

    threadA.start();

    System.out.println("start thread B");

    threadB.start();

    System.out.println("Start thread C");

    threadC.start();

    System.out.println("End of main thread");

    }

    l A d Th d

  • 8/10/2019 MultiThreading and Synchronization

    22/43

    class A extends Thread

    {

    public void run()

    {

    for(int i=1;i

  • 8/10/2019 MultiThreading and Synchronization

    23/43

    l Th dt t

  • 8/10/2019 MultiThreading and Synchronization

    24/43

    class Threadtest

    {

    public static void main(String args[])

    {

    A threadA=new A();

    B threadB= new B();

    threadB.setPriority(Thread.MAX_PRIORITY);

    threadA.setPriority(Thread.MIN_PRIORITY);

    System.out.println(start thread A);

    threadA.start();System.out.println(start thread B);

    threadB.start();

    }

  • 8/10/2019 MultiThreading and Synchronization

    25/43

    Using isAlive() and join()

    isAlive():

    final boolean isAlive()

    The isAlive() method returns true if the thread upon which it is

    called is still running. It returns false otherwise.

    join(): (wait for thread to terminate)

    final void join() throws InterruptedException

    This method waits until the thread on which it is called

    terminates.

  • 8/10/2019 MultiThreading and Synchronization

    26/43

    Example 3

    class A extends Thread

    {

    public void run()

    { for(int i=1;i

  • 8/10/2019 MultiThreading and Synchronization

    27/43

    Example 3

    class B extends Thread

    {

    public void run()

    {for(int j=1;j

  • 8/10/2019 MultiThreading and Synchronization

    28/43

    Example 3

    class ThreadMethods1{

    public static void main(String args[])

    { A threadA=new A();

    B threadB=new B();

    System.out.println("start thread A");

    threadA.call();

    System.out.println("start thread B");

    threadB.start();

    System.out.println("End of main thread");

    }

    }

  • 8/10/2019 MultiThreading and Synchronization

    29/43

    Example 3(Using Join()class ThreadMethods1

    {

    public static void main(String args[]){

    A threadA=new A();

    B threadB=new B();

    System.out.println("start thread A");

    threadA.call();System.out.println("start thread B");

    threadB.start();

    try{

    threadA.join();

    threadB.join();}

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

    }

    System.out.println("End of main thread");

    }

  • 8/10/2019 MultiThreading and Synchronization

    30/43

    Implementing Runnable

    Steps:

    1. Declare the class as implementing the Runnable

    interface.

    2. Implement the run() method.

    3. Create a thread by defining an object that is

    instantiated from this runnableclass as the target of

    the thread.

    4. Call the threadsstart() method to run the method.

  • 8/10/2019 MultiThreading and Synchronization

    31/43

    Example1(Runnable interface)

    class runnableex implements Runnable

    {

    public String t;

    runnableex(String s){t=s;}

    public void run()

    {

    for(int i=1;i

  • 8/10/2019 MultiThreading and Synchronization

    32/43

    class runnable1{

    public static void main(String args[])

    {runnableex ob1=new runnableex("FIRST");

    Thread thread1=new Thread(ob1);

    runnableex ob2=new runnableex("SECOND");Thread thread2=new Thread(ob2);

    System.out.println("thread1");

    thread1.start();

    System.out.println("thread2");

    thread2.start();

    System.out.println("End of main");

    }

    }

  • 8/10/2019 MultiThreading and Synchronization

    33/43

  • 8/10/2019 MultiThreading and Synchronization

    34/43

    class runnable1{

    public static void main(String args[])

    {runnableex ob1=new runnableex("FIRST");

    Thread thread1=new Thread(ob1); //step3

    runnableex ob2=new runnableex("SECOND");

    Thread thread2=new Thread(ob2);

    System.out.println("thread1");

    thread1.start(); //step4

    System.out.println("thread2");

    thread2.start();

    System.out.println("End of main");

    }

    }

  • 8/10/2019 MultiThreading and Synchronization

    35/43

    Example2(using Runnable

    interface)

    class runnableex2 implements Runnable{

    public String t;

    runnableex2(String s){t=s;}

    public void run()

    {

    for(int i=1;i

  • 8/10/2019 MultiThreading and Synchronization

    36/43

    Example2(using Runnable

    interface)

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

    {

    runnableex2 ob1=new runnableex2("FIRST");

    Thread thread1=new Thread(ob1);

    runnableex2 ob2=new runnableex2("SECOND");

    Thread thread2=new Thread(ob2);

    System.out.println("thread1");

    ob1.get1(thread1);

    System.out.println("thread2");

    ob2.get1(thread2);

    System.out.println("End of main");

    }

  • 8/10/2019 MultiThreading and Synchronization

    37/43

    Synchronization

    When two or more threads needs access to a shared resource, they

    need some way to ensure that the resource will be used by only one

    thread at a time. The process by which this is achieved is called

    synchronization.

    Key to synchronization is the concept of the monitor (semaphore). Amonitor is an object that is used as a mutually exclusive lock or

    mutex. Only one thread can own a monitor at a given time.

    When thread acquires a lock, it is said to have entered the monitor.

    All other threads attempting to enter the locked monitor will besuspended until the first thread exits the monitor. These other

    threads are said to be waiting for the monitor.

  • 8/10/2019 MultiThreading and Synchronization

    38/43

    The synchronized statement

    Synchronized method_name()

    {

    ----------------

    ----------------

    }

    OR

    Synchronized(object){//statement to be synchronized

    }

  • 8/10/2019 MultiThreading and Synchronization

    39/43

  • 8/10/2019 MultiThreading and Synchronization

    40/43

    class caller implements Runnable{

    String msg;

    Callme target;

    thread t;

    public caller(callme targ,String s){

    target=targ;

    msg=s;

    t=new Thread(this);

    t.start();}

  • 8/10/2019 MultiThreading and Synchronization

    41/43

    public void run()

    {

    synchronized(target){

    target.call(msg);

    }

    }}

    class synch1{

    public static void main(String args[]){

    callme target=new callme();caller ob1=new Caller(target,hello);

    caller ob2=new Caller(target,synchronized);

    caller ob3=new Caller(target,world);

    }

    }

  • 8/10/2019 MultiThreading and Synchronization

    42/43

    Using synchronized keyword

    Class callme{

    Synchronized void call(string msg){

    }

    This prevents other threads from entering call()

    while another thread is using it.

  • 8/10/2019 MultiThreading and Synchronization

    43/43

    Deadlock

    Thread A

    Synchronized method2()

    {

    Synchronized method1()

    {

    .

    .

    }

    }

    Thread B

    Synchronized method1(){

    Synchronized method2()

    {