Java Multithreading
In this tutorial, we will learn about what is multithreading and walk through on thread, thread scheduler, process vs threads and benefits of multithreading.
Multithreading
In Java, multithreading is a programming concept which explains on how to execute multiple threads concurrently within a single application, understanding this concept allows programmers to implement Threads on their application to perform different tasks under the same application at same time.
Multithreading concept broadly divided into following.
- What is thread.
- Thread creation.
- Thread scheduler
What is a Thread in multithreading:
A thread is a lightweight sub-process that runs concurrently with other threads within an application. Each of a thread has its own set of instructions to process, its own call stack, and its own program counter.
Threads Creation in multithreading:
Threads can be created in two ways in Java, as follows
- Extending the
java.lang.Thread
- By implementing the Runnable interface, and pass an instance of the implementation to a
java.lang.Thread
Extending java.lang.Thread
Class:
class MyThread extends Thread {
public void run() {
// set of instructions to process by the new thread
}
}
// initialize the newly created MyThread constructor
MyThread thread = new MyThread();
//calling the start method of java.lang.Thread class
thread.start();
By implementing the Runnable interface:
class MyRunnable implements Runnable {
public void run() {
// set of instructions to process by the new thread
}
}
// initialize the newly created MyRunnable constructor
MyRunnable runnable = new MyRunnable();
//pass MyRunnable instance to java.lang.Thread class constructor
Thread thread = new Thread(runnable);
//calling the start method of java.lang.Thread class
thread.start();
Thread Scheduler in multithreading:
Thread Scheduler is a component of the JVM, which decides on which thread to run on next. This follows scheduling algorithms to find which threads need to run, duration of thread execution and order of the thread.
Differences from process to threads :
Process | Threads |
---|---|
Its an instance of application running on a computer. | Thread is lightweight sub-process which runs as sub-process under the process. |
Heavy weight process | Lightweight sub-process |
Single task can be completed at a given time. | Multiple tasks can be completed at given time. |
High consumption of resources. | Less consumption of resources. |
Advantages of Multithreading:
- Tasks can be accomplished concurrently.
- Improved performance of the application.
- Utilization of less resources or less footprint.
- Easy to write applications with multithreading.
- Scalability.
- Better user interface, in case of UI based applications.
Conclusion:
In this tutorial, we have covered the concept of multithreading and its main components such Threads, Threads Scheduler, advantages of multithreading and differences from process vs threads.