MainMenu

Home Core Java Overview Maven Tutorials

Thursday, 11 April 2019

MultiThreading in java

MultiThreading in java





Multitasking and Multithreading


1). Multitasking refers to a computer's ability to perform multiple jobs concurrently. For Example :- more than one program are running concurrently.
2).A Thread is a single sequence of execution within a program.
MultiThreading in java is a process of executing multiple threads simultaneously.
Multithreading refers to multiple threads of control with in a single program.
Each program can run multiple threads of control within it.

A Thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading both are used to acheive multitasking.
Threads use a shared memory area but processes are not.
A thread is a lightweight subprocess, the 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 uses a shared memory area.
Java Multithreading is mostly used in games, animation etc.



For Example : Web browser is a program and its tabs are single thread.

Process :- An execution instance of a program is called a process. A thread is a subset of the process.

Advantage of Thread

1). To maintain responsiveness of an application during a long running task
2).To enable cancellation of separable tasks.
3).Some problems are intrinsically parallel.
4).To monitor status of some resource (DB)
5). Some APIs and Systems demand it : Swing.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple operations at the 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 an exception occurs in a single thread.

Application Thread

When we execute an application :-
The JVM creates a Thread object whose task is defined by the main() method.
It Starts the thread.
The thread executes the statements of the program one by one until the method returns and the thread dies.

Multiple Threads in an Application

Each thread has its private run-time stack
if two threads execute the same method, each will have its own copy of the local variables the methods uses.
However, all the threads see the same dynamic memory(heap)
Two different threads can act on the same object and same static fields concurrently.

Creating Thread

There are two ways to create our own Thread Object
1). By Extending Thread class OR Subclassing the Thread class and instantiating a new object of that class.
2). Implementing the Runnable interface.
In both the case the run() method should be implemented.

No comments:

Post a Comment