Friday 18 August 2017

Java Multithreading – Learn Everything That You Should Know part 1 ~ foundjava

Greetings friends, in this post we are going to explain Java multithreading, its pros, and cons, and the thread lifecycle. Next, you’ll get to see the details of thread class and its methods. Finally, learn how to create threads using thread class and runnable interface.
Also, we’ve supplemented the thread concepts with the help of state of the art examples and code samples. Now, before moving forward, let’s learn the basic meaning of a process and thread.
What is a process?
A process consists of a memory space allocated by the operating system that can contain one or more threads. The thread cannot exist on its own; it must be a part of a process. A process remains running until all of the non-daemon threads are done executing.
What is a thread?
  • The thread is a lightweight sub-process and the smallest unit of execution.
  • Each thread has a separate path of execution.
  • It shares the memory area of the process.
Let’s now get started and explore the world of multithreading.

Java Multithreading – Everything You Should Know.

What Is Multithreading In Java?

  • Java multithreading enables the execution of multiple threads simultaneously.
  • It allows a process to run its tasks in parallel mode on a single processor system.
Now one question you may ask that what made this concept so popular. To get clarity, let’s see the some of the benefits of using multithreading.
Java Multithreading Tutorial - Java Process and Threads
Java Process and Threads

What Are Pros And Cons Of Java Multithreading?

Pros.

  • General – It allows better use of system resources.
  • An important one – It allows parallel execution of tasks and thus saves execution time.
  • It provides enhanced performance on multi-processor machines.
  • Improvised GUI responsiveness.
  • Threads are independent and do not impact other threads of the same process if an exception occurs.
Multithreading doesn’t always yield benefits. It comes with its disadvantages too. Let us go through some of the typical after results.

Cons.

  • General – It results in the increased complexity of the code.
  • Synchronization of shared resources (objects, data) is CPU/memory intensive.
  • Debugging is hard because sometimes you can’t predict the results.
  • Increased potential for deadlock occurrence.
  • “Starvation” some of the threads may not be served with due to poor design.

What Is Thread Lifecycle In Java?

Java Multithreading Tutorial - Java Thread Life Cycle
Java Thread Life Cycle
Before moving on to creating a thread, we’ll first see the various phases through which the thread has to pass to complete its lifespan.
  • New
  • Runnable
  • Running
  • Non-Runnable (blocked)
  • Terminated
New- A thread is in New state when you create the instance of thread class but the start() method is yet to get called.
Runnable- The thread is in runnable after executing the start() method. In this stage, it waits for the thread scheduler to run it.
Running- A thread picked by the thread scheduler for execution remains in running state.
Non-Runnable (blocked)- In this state, the thread remains alive but it is not eligible to run. It may be due to some sleep operation, waiting for any File I/O to finish or in the locked state, etc.
Terminated- A thread is said to be in terminated state when its Run() method exits.
So far, you’ ve read the basic concepts of Java multithreading, let’s now move to learn the different ways to create threads.

How To Create Threads In Java?

In Java, we’ve got the following two ways to create threads.
It is important to learn that Java has supplied most of the thread functionality into the Thread class. So, before we jump to the thread creation part, let’s first understand the different features and methods available in the Thread class.

Java Thread Class Methods, Usage, And Examples.

Java accomplishes multithreading through its java.lang.Thread class. To become efficient in writing the multithreaded code you must know about the constructors and the methods of thread class before starting to write multithreading programs in Java.

List Of Thread Class Constructors.

Thread class has the following eight constructors.
Thread(): It creates a Thread object with a default name.
Thread(String name): It creates a Thread object with a name that the name argument specifies.
Thread (Runnable target): This method constructs Thread with a parameter of the Runnable object that defines the run() method.
Thread (Runnable target, String name): This method creates Thread with a name and a Runnable object parameter to set the run() method.
Thread(ThreadGroup group, Runnable target): It creates Thread object with a Runnable object and the group to which it belongs.
Thread (ThreadGroup group, Runnable target, String name): It creates Thread object with a Runnable object that defines the run() method, specified name as its name and the Thread object belongs to the ThreadGroup referred to by the group.
Thread(ThreadGroup group, String name): It creates a thread that has the specified name and associates to the ThreadGroup given as the first parameter.
Thread(ThreadGroup group, Runnable target, String name, long stackSize): this constructor specifies the ThreadGroup parameter, the size of the thread’s method-call stack.

General Methods To Manage The Threads.

Start():
When program calls start() method a new Thread is created and code inside run() method is executed in new Thread.
Run():
This method is the Entry point for the thread.
Let’s see a sample code that shows how to use the start() and run() methods.
String GetName():
You can use this method to get the name of the current thread.
SetName(String Name):
You can use to set the name of the thread.
During a debugging session, it’s helpful as we can distinguish between threads. By default, Java also sets the label for each Thread. Alternatively, you can also give a name to the Thread using the Thread constructor that takes the name as an argument. The method setName(String name) can also update the Thread name.
Let’s see a sample code that shows how to give a name to the Thread using the Thread(String name) constructor, setName(String name) method and retrieve that name in the run() method using getName() method.
Sample Code.
Sample Output.
If you forget to provide any name while running the code, you’ll see the following output.
If you give a name to a thread as “DemoThread” then the output will be.
Sleep(Long Milliseconds):
Suspends a thread for the specified period. If any other thread interrupts this sleeping thread, it will throw an InterruptedException. So it is suggested to enclose the sleep() method in the try block. Alternatively, the code’s method must include InterruptedException in its throws clause.
Boolean IsAlive():
It determines if a thread is still running. JVM considers thread to be alive immediately before calling to thread’s run() method, during the execution of thread’s run() and immediately after return from run().
During that interval, the isAlive() method returns a Boolean true value. Otherwise, it returns false.
isAlive() method is useful in the situations when one thread needs to wait for another thread to finish its run() method.
Let’s See A Sample Code For Sleep() And IsAlive() Method.
 Join(Long Milliseconds):
This method gets called when a thread wants to wait for another thread to terminate. Let’s see a sample code for the <join()> method.
Let’s See A Sample Code For The <Join()> Method.
Set Thread Types.
Threads fall under into following two categories.
  • User, and
  • daemon.
A user thread performs critical tasks that must finish before the application terminates. However, a daemon thread performs garbage collection and other background tasks. When an application’s starting thread (a user thread) ends, JVM checks whether any other user thread is running. If there is some running user thread, then JVM prevents the application from terminating. If there is no user thread running then JVM will terminate the application without bothering for the running daemon thread.
  • boolean isDaemon(): checks if the thread is a daemon thread.
  • setDaemon(boolean b): marks the thread as daemon or user thread. To start a daemon thread setDaemon(Boolean b) method must be called with an argument “true“.

No comments:

Post a Comment