Threads in Java

Bavatharany Mahathevan
8 min readOct 12, 2021

--

What is Process

The process is the execution of a program or an application. It allows doing the specified function of an application. A process can have a child process also.

What is Thread

Thread is a lightweight subset of the process and it is the flow of execution from start to end of a process. So that a process can contain multiple threads and two processes run on different memory spaces while all the threads share memory space.

Basically, we talk about two memories areas which are heap and stack. To know more about it refer to my previous article Java Virtual Machine Architecture.

Each thread will have its own stack, but all the threads in a process will share the heap.

An application should have at least one thread named as Main thread and java(java virtual machine )allows creating multi-threads as well.

Note: Every java application has at least one thread named main thread. Although there are so many other java threads running in the background like memory management, system management, signal processing etc. But from an application point of view — the main is the first java thread and we can create multiple threads from it.

What is multithread

Multithread is the meaning of having concurrency execution of threads. multithreaded is a type of multitasking. Actually, there are two types of multitasking available in java.

  1. process-based multitasking
  2. Thread based multitasking

Benefits of threads.

  1. Reduce development costs.
  2. Reduce maintenance costs.
  3. Reduce the complexity of an application.
  4. Increase the speed of CPUs.

What is the process-based multitasking

doing multi-functions at the same time. For example, in our windows os, we can run one or more applications at the same time like playing music, downloading movies and tying something on ms world .each process does not dependent on each other. It is considered process-based multitasking.

What is the Thread based multitasking

doing some functions within an application at the same time or having concurrent execution within an application is considered as Thread based multitasking. If many threads are executed then it is known as multithread. Suppose a particular application has to do some functions at the same time for efficiency and saving time, java allows it by using thread.

How can create a multithreaded program in Java.

There are two ways to create multithread programs in java

1. by extending the Thread class

2. by implementing Runnable interface.

The below image illustrates the advantages and disadvantages of using the two approaches

Let's see A brief explanation of the advantage and disadvantages of the two ways for creating a multithread program in java:

In that two approaches, if our class extends the Thread class, It can not extend any other class and if it already has the IS-A relationship with superclass, this relationship also will be broken by extending Thread class. Since the inheritance concept and Java does not support multiple inheritances.

While, If our class implements the Runnable interface, it can extend other classes. we can use the concept of inheritance. Therefore, Implementing a Runnable interface is considered as a most appropriate way to create a multithread program in java

How to create a thread by extending the Thread class

In order to achieve multithreading by extending the thread class, We have to do some following basic steps.

I. create our class then extend the java. lang.Thread and

II. override the run() which is available in the Thread class

III. Create an object for our class and call start() on this object

IV. The start() method invoke the run() method

the below code is for the basic idea to create a thread by extending the thread class.

As per our OOP concept, If a child class does not have an implementation for a method inside the class, it inherits from the parent class, Likewise, here, The printer. start() is also working. The Thread class has the start() method and invoke the run() method, but the run method does not have any implementation in the thread class. run() method is used to perform actions for the thread. So, if we want the thread to perform some actions, we must override the run() method and must have an implementation in the child class. In our case, the printer class overrides the run method itself.

How to create a thread by implementing a Runnable interface

In order to achieve multithreading by implementing a Runnable interface, We have to do some following basic steps.

I. We create a new class then implement java.lang.Runnable interface

II. It forces itself us to override the run() method.

III. Create an instance from the Thread class and pass the Runnable object then invoke the start() method from the thread object.

IV. The start() method invokes the run() method.

Runnable is a Functional interface, it has only one abstract method named the run() method. So, We can not call the start() method directly from our child class object or child thread, Hence, we have to create a Thread object by passing the runnable object as a parameter.

There are 8 ways to create thread objects with different constructor structures

  1. using default constructor Thread()
  2. using the constructor with Thread(Runnable object )
  3. using the construction with Thread(String name)
  4. Thread(Runnable object,string name)
  5. Thread(ThreadGroup group, Runnable target)
  6. Thread(ThreadGroup group, String name)
  7. Thread(ThreadGroup group, Runnable target, String name)
  8. Thread(ThreadGroup group, Runnable target, String name,

long stack size)

What are the common issues in multithread

As a multithread program allows to execute multiple tasks at the same time, there are some issues also .like complexity and difficulty to find bugs and provide unpredictable results etc.

For example,

1. when two threads are trying to modify and update one file.

2. when many threads are trying to access shared resources.

Priority of the Thread

Java virtual machine defines the priority for thread in java for thread value is [1..10]. the notable thing is priority value starts from 1, not from 0. In a computer system, only the index is beginning from 0 but the value starts from 1 obviously. The high priority value is 10, the low priority value is 0 and the mid-value is 5. The below image is from the Thread class.

The priority value for the thread

when we did not set a priority value for the main and child thread, JVM defines a default value for the main Thread because the system will create this thread as a value is 5 and the child thread takes the priority value of the main thread always.

when the main thread has priority value eight it is default or set value and the child does not have, the child threat will take the priority value of the main thread now also. hence, we can come into the consultation that the created thread will inherit the priority value from its parent thread.

When we set high priority for the child thread, most properly the child thread will be executed before the main thread execution.

when we set priority beyond the limit of priority value, there will be an exception thrown named Illegal Argument Exception.

When two thread has the same priority, they work like no priority value. However, we can not say that Thread will be executed based on our priority value, actually, the JVM has control over it. But we can get an idea of how to thread priority is working in the system.

Thread dumb is a way to know the state of the thread of a real program and it shows the contents of the thread's stack.

The life cycle of Thread

A thread goes through various phases in its lifecycle. The below image illustrates the overall life cycle of the thread

the life cycle of thread
  • New : a newly created thread that has not yet started the execution.
  • Runnable : Thread is ready for execution. The thread may be in a running or ready state. The threads will become in this state after calling the start() method on it but It is not selected by the thread scheduler.
  • Running : The thread is in executing state, performing the action. So that, the thread schedular scheduled the time to the thread.
  • Waiting : The thread waits for some other thread to perform a particular action without any time limit. if a thread is in the Waiting state then, there is no change to go directly in the running state, it has to go Ready /Runnable state.
  • Death: The thread is terminated after completed the execution.

The significant methods in Thread

  • strat() : method starts the new thread and send the thread into the Runnable state and invoke the run method as well.
  • run() : method is used to perform actions of the thread.
  • Join() : method means that the thread which is calling the join method, is going to wait until other threads die. It may wait for getting some resources from a particular thread or executing parallel with the particular thread.join() , join(long millis) , join(long millis, int nanos) are the three ways too use join() methods.
  • yield() : method does give a change to other thread to execute. for example Thread.yield() means that the particular thread is going to the waiting state and give the change to other threads.
  • sleep () : thread is going to sleep for a specific time and will be in the waiting state. there are two types of sleep() methods. sleep(long millis) , sleep(long millis, int nanos) are the two ways to use the sleep() method.
  • wait() : The wait() method tells the current thread to give up the lock and go to sleep until some other threads enter. The thread will provide the notify or notifyAll() methods. These all methods are defined in the Object class.

Unlike sleep() method, the wait() method, the thread goes in waiting state and it will not come back automatically until we call the notify() or notifyAll() method.

  • interrupt() : This method is for interrupting the threads that are in the waiting state. we have to call this method on which method needs to be interrupted and If the thread is not in sleeping, then it will wait until the thread goes in sleeping, once it comes to sleeping, it will be interrupted.
  • notify() : wakes up a single thread that is waiting on this object’s monitor.The notify() method is defined in Object class.

Q&A : what will happen when calling an interrupt() method on a thread which not sleep? it does not do any harm or not throw any exception.

  • But the interrupt will wait until the thread goes to sleep at some point.so that, the interrupt() method will interrupt the thread when it is just being to sleep.

Q&A : Can two threads access the same memory? yes

Reference

https://www.geeksforgeeks.org/multithreading-in-java/

--

--