What is Multi Threading ?
Multi threading in Java is a very important topic. I have written a lot about Threads in Java. Java Thread is a lightweight process that executes some task. Java provides multithreading support with the Thread class and an application can create multiple threads executing concurrently.
There are two types of threads in an application – user thread and daemon thread. When we start an application, main is the first user thread created and we can create multiple user threads as well as daemon threads. When all the user threads are executed, JVM terminates the program.
We can set different priorities to different Threads but it doesn’t guarantee that higher priority thread will execute first than lower priority thread. Thread scheduler is the part of Operating System implementation and when a Thread is started, it’s execution is controlled by Thread Scheduler and JVM doesn’t have any control on it’s execution.
We can create Threads by either implementing Runnable interface or by extending Thread Class.
Thread t = new Thread(new Runnable(){
@Override
public void run() {
}
});
Above is a one liner statement to create new Thread, Here we are creating Runnable as Anonymous Class,
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.
Threads in Java
With Java 8 lambda expressions, we can create Thread in java like below too because Runnable is a functional interface.
Thread t = new Thread(() -> {System.out.println("My Runnable");});
t.start();
No comments:
Post a Comment