Multithreading In Java

  • Multithreading in Java is a Process of Simultaneously executing Multiple threads.

  • Thread is basically a smallest unit of processing and a light weight sub-process. To achieve multitasking, multiprocessing and multi threadings are used.

  • As threads share a common memory area, we use multithreading than multiprocessing. They save memory as they don’t allocate separate memory and it takes less time than process in between the context – switching and threads.

  • In games, animations etc., Java Multithreading is mostly used.

Advantages of Java Multithreading:

  • Threads are independent as it does not block the user, and sometimes you can perform multiple operation.

  • To some more time you can perform many operations together.

  • If exception occur in a single thread it doesn’t other thread as threads are independent.

Multi tasking:

  • Multi tasking is a process of simultaneous executing multiple tasks. To utilize the CPU multiple tasking is used.

  • Process- based Multiple tasking

  • Thread- based Multiple tasking are the two ways in which multiple tasking can be achieved.

Process- based Multi tasking:

  • Each process allocates separate memory area i.e in memory each process has its own address.

  • Process is heavy weight.

  • High cost of communication between the process.

  • For saving and loading registers, Updating lists, memory maps etc., requires some time for switching from one process to another.

Thread- based Multi-tasking:

  • Same address space is shared by the threads.

  • Thread is lightweight

  • Low cost of communication within the thread.

What is a Thread in Java:

A thread is a smallest unit in processing and a light weight sub process. For execution it is a separate part.

It doesn’t affect other thread if there occurs exception in one thread when threads are independent, common memory area is shared.

How to create thread

  • By extending thread class

  • By implementing Runable interface are the two ways to create a thread.

  • Thread class:

  • To create and perform operations on the thread. Constructors and methods are provided by the thread class.

Runnable Interface:

By thread whose instances are intended to be executed in which the runnable should be implemented by any class.

Run() is only one method which is only named by the runnable interface.

Starting a thread:

To start a newly created thread a start() method of thread class is used.

Naming thread:

To change and get the name of a thread, the thread class provides methods. Thread-0, thread-1 and so on are the names of the each thread by default. By using setName() method we can change the name of the thread.

Visit for java training in vizag

Polymorphism in Java

Modifiers in Java

Java Inheritance