1 of 34

Java - Multithreading

2 of 34

  • Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.
  • Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.

3 of 34

4 of 34

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.

5 of 34

  • 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)

6 of 34

7 of 34

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.

8 of 34

Thread-based Multitasking (Multithreading)

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

9 of 34

10 of 34

11 of 34

Threads can be created by using two mechanisms :

  1. Extending the Thread class

  • Implementing the Runnable Interface�

12 of 34

13 of 34

Extending the Thread class�

1)We create a class that extends the java.lang.Thread class.

2)This class overrides the run() method available in the Thread class.

3) A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread.

4)Start() invokes the run() method on the Thread object.�

14 of 34

Thread creation by implementing the Runnable Interface

1)We create a new class which implements java.lang.Runnable interface

2) override run() method.

3) Create a thread by defining an object that instantiated from this runnable class as the target of the thread.

4) Then call start() method on this object to run the thread.

15 of 34

16 of 34

Thread Class vs Runnable Interface

  1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.

  • We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.�� 

17 of 34

Life cycle of a Thread (Thread States)

18 of 34

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(Dead): A thread is in terminated or dead state when its run() method exits.

19 of 34

Methods of Thread class

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

public void stop(): it is used to stop the thread (deprecated).

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

20 of 34

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

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

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

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

public void wait(): It has been told to wait some event occurs.

21 of 34

public void notify(): A thread which goes into waiting state by calling wait() method will be in waiting state until any other thread calls notify()

public void notifyall(): A thread which goes into waiting state by calling wait() method will be in waiting state until any other thread calls notifyall()

Note:

We can use notify() method to give the notification for only one thread which is waiting for a particular object whereas by the help of notifyAll() methods we can give the notification to all waiting threads of a particular object.

22 of 34

public void setName(): is used to set names to created thread.

public void getName(): is used to get the name of the thread.

public void getState(): is used to get the current state of the thread

.

23 of 34

Thread Priorities

Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases, thread schedular schedules the threads according to their priority (known as preemptive scheduling).

But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.

24 of 34

3 constants defined in Thread class

  • public static int MIN_PRIORITY
  • public static int NORM_PRIORITY
  • public static int MAX_PRIORITY

  • Default priority of a thread is 5 (NORM_PRIORITY).
  • The value of MIN_PRIORITY is 1.
  • The value of MAX_PRIORITY is 10.

25 of 34

26 of 34

Daemon Thread

  • Daemon thread in java is a service provider thread that provides services to the user thread.

Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically.

There are many java daemon threads running automatically e.g. gc, finalizer etc.

27 of 34

Points to remember for Daemon Thread in Java

  • It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.
  • Its life depends on user threads.
  • It is a low priority thread.

28 of 34

Methods for Java Daemon thread by Thread class

public void setDaemon(boolean status):

it is used to mark the current thread as daemon thread or user thread.

public boolean isDaemon():

it is used to check that current is daemon.

29 of 34

ThreadGroup in Java

Java provides a convenient way to group multiple threads in a single object. In such way, we can suspend, resume or interrupt group of threads by a single method call.

30 of 34

Constructors of ThreadGroup class

  • ThreadGroup(String name):creates a thread group with given name.
  • ThreadGroup(ThreadGroup parent, String name): creates a thread group with given parent group and name.

31 of 34

Important methods of ThreadGroup class

int activeCount():returns no. of threads running in current group.

int activeGroupCount():returns a no. of active group in this thread group.

void destroy():destroys this thread group and all its sub groups.

String getName():returns the name of this group.

ThreadGroup getParent():returns the parent of this group.

void interrupt():interrupts all threads of this group.

void list():prints information of this group to standard console.

32 of 34

Synchronization in Java�

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.

33 of 34

Uses of Synchronization�

The synchronization is mainly used to

  • To prevent thread interference.
  • To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

  • Process Synchronization
  • Thread Synchronization

34 of 34

Thread Synchronization�

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

  • Mutual Exclusive
    • Synchronized method.
    • Synchronized block.
  • Cooperation (Inter-thread communication in java)