Blog about Programming Languages & Coding

Blog about Programming Languages & Coding
Contents for Computer Science, IT, B.Sc. CS & IT, M.Sc. CS & IT, MCA, BE CS & IT, ME CS & IT , Interview Questions, Books and Online Course Recommendations from Udemy, Coursera, etc

Multithreading in Java

 Multithreading in Java

 Multithreading in java is a process of executing multiple threads simultaneously.

Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation etc.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple operations at same time.

2) You can perform many operations together so it saves time.

3) Threads are independent so it doesn't affect other threads if exception occur in a single thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways:

  • Process-based Multitasking(Multiprocessing)
  • Thread-based Multitasking(Multithreading)

1) Process-based Multitasking (Multiprocessing)

  • Each process have its own address in memory i.e. each process allocates separate memory area.
  • Process is heavyweight.
  • Cost of communication between the process is high.
  • Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc.

2) Thread-based Multitasking (Multithreading)

  • Threads share the same address space.
  • Thread is lightweight.
  • Cost of communication between the thread is low.

Note: At least one process is required for each thread.

What is Thread in java

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution.

Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It shares a common memory area.

multithreading.JPG

As shown in the above figure, thread is executed inside the process. There is context-switching between the threads. There can be multiple processes inside the OS and one process can have multiple threads.

Note: At a time one thread is executed only.

Life cycle of a Thread (Thread States)

A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in java new, runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:

  1. New
  2. Runnable
  3. Running
  4. Non-Runnable (Blocked)
  5. Terminated

threadstates.jpg

1) New

The thread is in new state if you create an instance of Thread class but before the invocation of start() method.

2) Runnable

The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.

How to create thread

There are two ways to create a thread:

  1. By extending Thread class
  2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

o    Thread()

o    Thread(String name)

o    Thread(Runnable r)

o    Thread(Runnable r,String name)

Commonly used methods of Thread class:

1.   public void run(): is used to perform action for a thread.

2.   public void start(): starts the execution of the thread.JVM calls the run() method on the thread.

3.   public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.

4.   public void join(): waits for a thread to die.

5.   public void join(long miliseconds): waits for a thread to die for the specified miliseconds.

6.   public int getPriority(): returns the priority of the thread.

7.   public int setPriority(int priority): changes the priority of the thread.

8.   public String getName(): returns the name of the thread.

9.   public void setName(String name): changes the name of the thread.

10.         public Thread currentThread(): returns the reference of currently executing thread.

11.         public int getId(): returns the id of the thread.

12.         public Thread.State getState(): returns the state of the thread.

13.         public boolean isAlive(): tests if the thread is alive.

14.         public void yield(): causes the currently executing thread object to temporarily pause and allow other threads to execute.

15.         public void suspend(): is used to suspend the thread(depricated).

16.         public void resume(): is used to resume the suspended thread(depricated).

17.         public void stop(): is used to stop the thread(depricated).

18.         public boolean isDaemon(): tests if the thread is a daemon thread.

19.         public void setDaemon(boolean b): marks the thread as daemon or user thread.

20.         public void interrupt(): interrupts the thread.

21.         public boolean isInterrupted(): tests if the thread has been interrupted.

22.         public static boolean interrupted(): tests if the current thread has been interrupted.

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run().

 

1.   public void run(): is used to perform action for a thread.


Starting a thread:

start() method of Thread class is used to start a newly created thread. It performs following tasks:

o    A new thread starts(with new callstack).

o    The thread moves from New state to the Runnable state.

o    When the thread gets a chance to execute, its target run() method will run.


1) Java Thread Example by extending Thread class

1.   class Multi extends Thread{  

2.   public void run(){  

3.   System.out.println("thread is running...");  

4.   }  

5.   public static void main(String args[]){  

6.   Multi t1=new Multi();  

7.   t1.start();  

8.    }  

9.   }  

Output:thread is running...


2) Java Thread Example by implementing Runnable interface

1.   class Multi3 implements Runnable{  

2.   public void run(){  

3.   System.out.println("thread is running...");  

4.   }  

5.     

6.   public static void main(String args[]){  

7.   Multi3 m1=new Multi3();  

8.   Thread t1 =new Thread(m1);  

9.   t1.start();  

10. }  }  

Output:thread is running...

If you are not extending the Thread class,your class object would not be treated as a thread object.So you need to explicitely create Thread class object.We are passing the object of your class that implements Runnable so that your class run() method may execute.

 

Sleep method in java

The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

Syntax of sleep() method in java

The Thread class provides two methods for sleeping a thread:

  • public static void sleep(long miliseconds)throws InterruptedException
  • public static void sleep(long miliseconds, int nanos)throws InterruptedException

Example of sleep method in java

1.   class TestSleepMethod1 extends Thread{  

2.    public void run(){  

3.     for(int i=1;i<5;i++){  

4.       try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}  

5.       System.out.println(i);  

6.     }  

7.    }  

8.    public static void main(String args[]){  

9.     TestSleepMethod1 t1=new TestSleepMethod1();  

10.  TestSleepMethod1 t2=new TestSleepMethod1();  

11.     t1.start();  

12.  t2.start();  

13. }  

14.

 

Output:

       1
       1
       2
       2
       3
       3
       4
       4

As you know well that at a time only one thread is executed. If you sleep a thread for the specified time,the thread shedular picks up another thread and so on.

Synchronization in Java

·         Multithreading introduces asynchronous behavior to the programs. If a thread is writing some data another thread may be reading the same data at that time. This may bring inconsistency.

·         When two or more threads need access to a shared resource there should be some way that the resource will be used only by one resource at a time. The process to achieve this is called synchronization.

·         To implement the synchronous behavior java has synchronous method. Once a thread is inside a synchronized method, no other thread can call any other synchronized method on the same object. All the other threads then wait until the first thread come out of the synchronized block.

·         When we want to synchronize access to objects of a class which was not designed for the multithreaded access and the code of the method which needs to be accessed synchronously is not available with us, in this case we cannot add the synchronized to the appropriate methods. In java we have the solution for this, put the calls to the methods (which needs to be synchronized) defined by this class inside a synchronized block in following manner.

Synchronized(object)
{
    // statement to be synchronized
}

 

Synchronization in java is the capability to control the access of multiple threads to any shared resource.

Java Synchronization is better option where we want to allow only one thread to access the shared resource.

Why use Synchronization

The synchronization is mainly used to

  1. To prevent thread interference.
  2. To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

  1. Process Synchronization
  2. Thread Synchronization

Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread communication.

  1. Mutual Exclusive
    1. Synchronized method.
    2. Synchronized block.
    3. static synchronization.
  2. Cooperation (Inter-thread communication in java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by three ways in java:

  1. by synchronized method
  2. by synchronized block
  3. by static synchronization

Concept of Lock in Java

Synchronization is built around an internal entity known as the lock or monitor. Every object has an lock associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them.

From Java 5 the package java.util.concurrent.locks contains several lock implementations.


Understanding the problem without Synchronization

In this example, there is no synchronization, so output is inconsistent. Let's see the example:

1.   Class Table{  

2.     void printTable(int n){//method not synchronized  

3.      for(int i=1;i<=5;i++){  

4.        System.out.println(n*i);  

5.        try{  

6.         Thread.sleep(400);  

7.        }catch(Exception e){System.out.println(e);}  

8.      }   }  }  

9.     

10.class MyThread1 extends Thread{  

11.Table t;  

12.MyThread1(Table t){  

13.this.t=t;  

14.}  

15.public void run(){  

16.t.printTable(5);  

17.}}  

18.class MyThread2 extends Thread{  

19.Table t;  

20.MyThread2(Table t){  

21.this.t=t;  

22.}  

23.public void run(){  

24.t.printTable(100);  

25.}}  

26.  

27.class TestSynchronization1{  

28.public static void main(String args[]){  

29.Table obj = new Table();//only one object  

30.MyThread1 t1=new MyThread1(obj);  

31.MyThread2 t2=new MyThread2(obj);  

32.t1.start();  

33.t2.start();  

34.}}  

Output: 5

       100

       10

       200

       15

       300

       20

       400

       25

       500

      

Java synchronized method

If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.

1.   //example of java synchronized method  

2.   class Table{  

3.    synchronized void printTable(int n){//synchronized method  

4.      for(int i=1;i<=5;i++){  

5.        System.out.println(n*i);  

6.        try{  

7.         Thread.sleep(400);  

8.        }catch(Exception e){System.out.println(e);}  

9.      }    }  }  

10.  

11.class MyThread1 extends Thread{  

12.Table t;  

13.MyThread1(Table t){  

14.this.t=t;  

15.}  

16.public void run(){  

17.t.printTable(5);  

18.}  }  

19.class MyThread2 extends Thread{  

20.Table t;  

21.MyThread2(Table t){  

22.this.t=t;  

23.}  

24.public void run(){  

25.t.printTable(100);  

26.}  }  

27.  

28.public class TestSynchronization2{  

29.public static void main(String args[]){  

30.Table obj = new Table();//only one object  

31.MyThread1 t1=new MyThread1(obj);  

32.MyThread2 t2=new MyThread2(obj);  

33.t1.start();  

34.t2.start();  

35.}  }  

Output: 5

       10

       15

       20

       25

       100

       200

       300

       400

       500

      

Synchronized block in java

Synchronized block can be used to perform synchronization on any specific resource of the method.

Suppose you have 50 lines of code in your method, but you want to synchronize only 5 lines, you can use synchronized block.

If you put all the codes of the method in the synchronized block, it will work same as the synchronized method.

Points to remember for Synchronized block

  • Synchronized block is used to lock an object for any shared resource.
  • Scope of synchronized block is smaller than the method.

 

 

Syntax to use synchronized block

1.   synchronized (object reference expression) {   

2.     //code block   

3.   }  

Example of synchronized block

1.   class Table{  

2.    void printTable(int n){  

3.      synchronized(this){//synchronized block  

4.        for(int i=1;i<=5;i++){  

5.         System.out.println(n*i);  

6.         try{  

7.          Thread.sleep(400);  

8.         }catch(Exception e){System.out.println(e);}  

9.        }     }  

10. }//end of the method  

11.}  

12.  

13.class MyThread1 extends Thread{  

14.Table t;  

15.MyThread1(Table t){  

16.this.t=t;  

17.}  

18.public void run(){  

19.t.printTable(5);  

20.}   

21.}  

22.class MyThread2 extends Thread{  

23.Table t;  

24.MyThread2(Table t){  

25.this.t=t;  

26.}  

27.public void run(){  

28.t.printTable(100);  

29.}  

30.}  

  

31.public class TestSynchronizedBlock1{  

32.public static void main(String args[]){  

33.Table obj = new Table();//only one object  

34.MyThread1 t1=new MyThread1(obj);  

35.MyThread2 t2=new MyThread2(obj);  

36.t1.start();  

37.t2.start();  

38.}  

39.}  

Output:5
       10
       15
       20
       25
       100
       200
       300
       400
       500
       

Inter-thread communication in Java

We have few methods through which java threads can communicate with each other. These methods are wait(), notify(), notifyAll(). All these methods can only be called from within a synchronized method.
1) To understand synchronization java has a concept of monitor. Monitor can be thought of as a box which can hold only one thread. Once a thread enters the monitor all the other threads have to wait until that thread exits the monitor.
2)
 wait()  tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify().
3)
 notify() wakes up the first thread that called wait() on the same object.
notifyAll()
 wakes up all the threads that called wait() on the same object. The highest priority thread will run first.

Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed.It is implemented by following methods of Object class:

  • wait()
  • notify()
  • notifyAll()

1) wait() method

Causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it will throw exception.

Method

Description

public final void wait()throws InterruptedException

waits until object is notified.

public final void wait(long timeout)throws InterruptedException

waits for the specified amount of time.

2) notify() method

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. Syntax:

public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor. Syntax:

public final void notifyAll()

Understanding the process of inter-thread communication

inter thread communication in java interthread.gif

The point to point explanation of the above diagram is as follows:

 

  1. Threads enter to acquire lock.
  2. Lock is acquired by on thread.
  3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it releases the lock and exits.
  4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable state).
  5. Now thread is available to acquire lock.
  6. After completion of the task, thread releases the lock and exits the monitor state of the object.

Difference between wait and sleep:

wait()

sleep()

wait() method releases the lock

sleep() method doesn't release the lock.

is the method of Object class

is the method of Thread class

is the non-static method

is the static method

is the non-static method

is the static method

should be notified by notify() or notifyAll() methods

after the specified amount of time, sleep is completed.

Example of inter thread communication in java

1.   class Customer{  

2.   int amount=10000;  

3.   synchronized void withdraw(int amount){  

4.   System.out.println("going to withdraw...");  

5.     

6.   if(this.amount<amount){  

7.   System.out.println("Less balance; waiting for deposit...");  

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

9.   }  

10.this.amount-=amount;  

11.System.out.println("withdraw completed...");  

12.}  

13.  

14.synchronized void deposit(int amount){  

15.System.out.println("going to deposit...");  

16.this.amount+=amount;  

17.System.out.println("deposit completed... ");  

18.notify();  

19.}  

20.}  

21.  

22.class Test{  

23.public static void main(String args[]){  

24.final Customer c=new Customer();  

25.new Thread(){  

26.public void run(){c.withdraw(15000);}  

27.}.start();  

28.new Thread(){  

29.public void run(){c.deposit(10000);}  

30.}.start();  

31.  

32.}}  

Output: going to withdraw...
       Less balance; waiting for deposit...
       going to deposit...
       deposit completed...
       withdraw completed
  

 

 

Method 1: Thread creation by extending Thread class

Example 1:

class MultithreadingDemo extends Thread

  public void run(){ 

    System.out.println("My thread is in running state."); 

  }  

  public static void main(String args[]){ 

     MultithreadingDemo obj=new MultithreadingDemo();  

     obj.start(); 

  } 

}

Output:

My thread is in running state.

Example 2:

class Count extends Thread

{

   Count()

   {

     super("my extending thread");

     System.out.println("my thread created" + this);

     start();

   }

   public void run()

   {

     try

     {

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

        {

           System.out.println("Printing the count " + i);

           Thread.sleep(1000);

        }

     }

     catch(InterruptedException e)

     {

        System.out.println("my thread interrupted");

     }

     System.out.println("My thread run is over" );

   }

}

class ExtendingExample

{

   public static void main(String args[])

   {

      Count cnt = new Count();

      try

      {

         while(cnt.isAlive())

         {

           System.out.println("Main thread will be alive till the child thread is live");

           Thread.sleep(1500);

         }

      }

      catch(InterruptedException e)

      {

        System.out.println("Main thread interrupted");

      }

      System.out.println("Main thread's run is over" );

   }

}

Output:

my thread createdThread[my runnable thread,5,main]

Main thread will be alive till the child thread is live

Printing the count 0

Printing the count 1

Main thread will be alive till the child thread is live

Printing the count 2

Main thread will be alive till the child thread is live

Printing the count 3

Printing the count 4

Main thread will be alive till the child thread is live

Printing the count 5

Main thread will be alive till the child thread is live

Printing the count 6

Printing the count 7

Main thread will be alive till the child thread is live

Printing the count 8

Main thread will be alive till the child thread is live

Printing the count 9

mythread run is over

Main thread run is over

Method 2: Thread creation by implementing Runnable Interface

A Simple Example

class MultithreadingDemo implements Runnable

  public void run(){ 

    System.out.println("My thread is in running state."); 

  }  

  public static void main(String args[]){ 

     MultithreadingDemo obj=new MultithreadingDemo(); 

     Thread tobj =new Thread(obj); 

     tobj.start(); 

 } 

}

Output:

My thread is in running state.

Example Program 2:
Observe the output of this program and try to understand what is happening in this program. If you have understood the usage of each thread method then you should not face any issue, understanding this example.

class Count implements Runnable

{

   Thread mythread ;

   Count()

   {

      mythread = new Thread(this, "my runnable thread");

      System.out.println("my thread created" + mythread);

      mythread.start();

   }

   public void run()

   {

      try

      {

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

        {

          System.out.println("Printing the count " + i);

          Thread.sleep(1000);

        }

     }

     catch(InterruptedException e)

     {

        System.out.println("my thread interrupted");

     }

     System.out.println("mythread run is over" );

   }

}

class RunnableExample

{

    public static void main(String args[])

    {

       Count cnt = new Count();

       try

       {

          while(cnt.mythread.isAlive())

          {

            System.out.println("Main thread will be alive till the child thread is live");

            Thread.sleep(1500);

          }

       }

       catch(InterruptedException e)

       {

          System.out.println("Main thread interrupted");

       }

       System.out.println("Main thread run is over" );

    }

}

Output:

my thread createdThread[my runnable thread,5,main]

Main thread will be alive till the child thread is live

Printing the count 0

Printing the count 1

Main thread will be alive till the child thread is live

Printing the count 2

Main thread will be alive till the child thread is live

Printing the count 3

Printing the count 4

Main thread will be alive till the child thread is live

Printing the count 5

Main thread will be alive till the child thread is live

Printing the count 6

Printing the count 7

Main thread will be alive till the child thread is live

Printing the count 8

Main thread will be alive till the child thread is live

Printing the count 9

mythread run is over

Main thread run is over

 


Multithreading in Java Multithreading in Java Reviewed by Asst. Prof. Sunita Rai, Computer Sci.. Dept., G.N. Khalsa College, Mumbai on January 13, 2022 Rating: 5

No comments:

Powered by Blogger.