Showing posts with label java multithreading. Show all posts
Showing posts with label java multithreading. Show all posts

Friday, March 1, 2024

MULTITHREADING IN JAVA

 Java Multithreading


  • ADVANTAGES
  • PROCESS BASED MULTITASKING
  • THREAD BASED MULTITASKING
  • USE OF THREAD
  • JAVA THREAD CLASS 
  • JAVA THREAD METHOD
  • THREAD VC RUNNABLE CLASS 
  • LIFE CYCLE OF THREAD
  • JAVA THREAD PRIORITY IN MULTITHREADING

Java's multithreading functionality allows for the simultaneous execution of several threads. The smallest processing unit is a thread, which is a light subprocess. Multiprocessing and multithreading are used to do several tasks at once.

Because threads can benefit from shared memory, multithreading is favored over multiprocessing. By not creating a specific region, they preserve memory, and thread context swapping is faster than process execution. Java multithreading is widely used in games, animations, and other related tasks.

Advantages of multithreading: -

  1. The user won't be hampered since threads are autonomous and allow many apps to execute at once.
  2. It saves time to perform many tasks at once.
  3. Other threads are independent, therefore this won't affect them in any way. procedures when a single thread encounters an issue.

Multitasking is of two types: -

  • Process-based multitasking (Multiprocessing)
  • Thread based multitasking (Multithreading)

Process-based multitasking

  • Each process has an address in memory. In other words, each process allocates a separate area of ​​memory.
  • The process is heavy.
  • The cost of transferring data between processes is high.
  • Switching from one process to another requires some time to save and load registers, memory cards. . , and lists. , and so on.

Thread-based multitasking (Multithreading)

  •       Threads share the same address space.
  •       Threading is lightweight.
  •       Communication between threads is low.

What is the use of thread in Java?

A thread is a light subprocess that is the smallest processing unit. We have a separate execution path here.

Threads operate on their own. One thread may experience an exception without impacting the others. It utilizes a section of shared memory.

At runtime, several threads can switch contexts. inside an operating system, there can be several processes and multiple threads inside a single process.

Java thread class

Java has a class called Thread this Thread class is used for thread programming. You may create and execute thread activities using the constructors and methods that the Thread class offers. The Thread class makes use of the Runnable interface to enhance other classes' capabilities.

Java thread methods


 


Thread creation by implementing the runnable interface

The java. lang package will be implemented by a newly formed class. creates a runnable interface and substitutes our own run() method for the run() function. The Thread object is then created, and its start() function is called.

Let us understand by a program

// the Runnable Interface

Thread class Vs Runnable class

Java does not enable multiple inheritance; therefore our expanded Thread class is unable to extend any other classes. Once we implement the Runnable interface, our class still can extend to other base classes.

Basic thread functionality can be achieved by extending the Thread class, as it provides some built-in methods such as produce(), interrupt(), etc., these methods are not available in the Runnable interface.

When you use the runnable command, an object that may be shared by several threads is produced.

The life cycle of a Thread (Thread states)

A thread lies only in one of the shown states at any instant:

1.      New State

2.      Runnable State

3.      Blocked State

4.      Waiting State

5.      Timed Waiting State

6.      Terminated State

Let us understand each one of them separately:

New thread: A new thread when it is created goes into a new state. When a thread gets to this point, it hasn't started yet. If and only if a thread's code hasn't begun, it is said to be in a fresh state.

Running state: A thread enters the running state when it's ready to go. The thread may currently be operating, or it may be ready to start running at any time. The thread scheduler's role is to determine when the thread will execute.

In a multithreaded program, time is assigned to each thread separately. Each thread runs for a certain length of time before halting and handing the CPU to another thread so that additional threads can operate. Every thread that is ready for the CPU to run waits patiently for the CPU to execute an active thread when this happens.

Blocked: Right now, one thread is unable to obtain the lock, while another thread is managing to accomplish so. A thread changes from being blocked to being in the running state when it is locked.

Waiting state: A thread has to invoke the wait() or join() method to go into the waiting state. It goes into the running state when it gets a notification from another thread or when that thread ends.

Timed Wait: Calling a method with a timeout parameter causes a thread to be scheduled to wait. We refer to this as a timed wait. The thread will remain in this state until it times out or gets a notification. If a thread calls for anything like sleep or a conditional wait, it's put into a timed wait.

Terminated state: A thread may quit its current state if any of the following circumstances are met: It conventionally departs the body. This takes place once the thread's code has finished running.

Because of the appearance of an unforeseen issue, such as a segment fault or an exception that was ignored.

Implementing thread states in Java

To find out the current status of a thread while dealing with Java, use the Thread.getState() method. It includes the java.lang library. The state variables are defined as an enumeration by the Thread class. It is summarized below.

1)      1) NEW

It means the thread has not started yet

Ex: public static final Thread.State NEW
 
2)      Runnable 
 
The thread state of the running thread. In executable mode, a thread starts in the Java 
virtual machine, but can wait for other operating system resources, such as the CPU.
Ex. public static final Thread.State RUNNABLE
 
3)      Blocked 
A thread goes into a blocked state while it waits for the screen lock to be imposed. 
A thread cannot leave a blocked state unless it invokes an Object to return to a 
synchronized block or function, or it must wait for the screen lock to move to a 
synchronized block or Object. wait().
Ex. public static final Thread. State BLOCKED
 
4)      Waiting 
Thread state for a waiting thread. A thread is waiting because it calls one of the 
following methods: Object. wait with no timeout thread. Join with no 
timeout LockSupport.park.
 
Ex. public static final Thread.State WAITING
 
5)      Timed waiting 
The condition of a thread that is waiting for a given amount of time. When a thread 
calls one of the following methods with a positive timeout provided, the thread times 
out while it waits: Thread.sleepObject.wait with timeout thread. join with 
timeoutLockSupport.parkNanosLockSupport.parkUntil.
 
Ex. public static final Thread.State TIMED_WAITING
 
6)      Terminated 
 
Thread state of the finished thread. The thread is ready.
 
Ex. public static final Thread.State TERMINATED

 

Below is the implementation of the thread:

// Java program to demonstrate thread states


 





Java thread priority in multithreading
Thread scheduling is the process of allocating a processor to a thread according to its 
priority; As we already studied Java is an OOP language that runs in a multi-threaded 
environment. In Java, priority is assured at the time of thread creation. Programmers 
have the option to manually designate a priority during thread formation, or the JVM 
can do it for them automatically.
Each thread in this context has a priority, which is expressed as a number between 1 and 10,
or, to put it more simply, each object has a priority.
The exception is default priority is 5. Minimum priority is 1. Maximum priority is 10. 
Here 3 constants are defined in it as follows:\public static int NORM_PRIORITY\public 
static int MIN_PRIORITY\ public static int MAX_PRIORITY
To find out how the task is done inside, let's talk about it using an example. Here, we make 
the following use of the data gathered above: 

We use the current Thread() method to know the name of the current thread. The developer can also use the setName() method if they want to name the threads according to the option for understanding.getName() method is used to get the thread name.

The accepted priority value of a thread is between 1-10.

Let's discuss how we can get and prioritize a thread in Java. public final int getPriority(): The method java. lang.Thread.getPriority() gives the priority of the given thread.public final void set Priority(int newPriority): The method java.lang.Thread.setPriority() sets the preference of the thread to a new thread priority. This method throws an IllegalArgumentException if the value of the new Priority parameter exceeds the min(1) and max(10) limits.

Let us have a program to understand this:

Let us have a program to understand this:




Output Explanation:

The highest priority thread can execute first when thread execution is prioritized. Assume that the priorities of threads 1, 2, and 3 are 4, 6, and 1, respectively. As a result, thread t2 is started with a maximum priority of 6, and then thread t1 and thread t3 come next. The priority of the main thread always remains 5, however, it can be modified at a later time. Every other thread's default priority is set by the priority of the main thread.

What happens if we assign the same priority to every thread, you might wonder. All thread handling is done using the thread scheduler. The example below of what happens when the priorities are the same can be referred to and discussed later as an explanation of the result to better understand conceptually and practically.

COLLECTIONS IN JAVA

 Collections in Java


  • FRAMEWORKS
  • ADVANTAGES OF JAVA COLLECTION FRAMEWORK
  • METHODS OF COLLECTION INTERFACE
  • LINKED LIST
  • VECTOR
  • STACK
  • QUEUE INTERFACE
  • SET INTERFACE
  • CLASSES THAT IMPLEMENT THE SET INTERFACE( HARSH SET, SORTED SET, MAP, ETC)

Java's Collection framework may be used to store and manage collections of objects.

Java Collections may be used for data operations such as sorting, searching, inserting, modifying, and removing. In Java, an object collection is called a collection. The Java Collection foundation includes classes and interfaces including Vector, LinkedList, Priority Queue, HashSet, LinkedHashSet, and TreeSet.

Framework in Java

An architecture that has already been created for a group of classes and interfaces is called a framework. It is not necessary to define a framework to add a new class or function. But with a perfect object-oriented design, there is always a framework with classes in it, so every class does the same job.

Java's unique collection structure is required

Arrays, vectors, and hash tables were the usual Java ways for objects (or collections) before the introduction of the collection framework (or JDK 1.2). All of these collections lacked a single, cohesive user interface. As a result, even while every collection aims to achieve the same general objective, each collection's implementation was decided upon independently of the others. Not to mention how hard it is for users to remember the distinct constructors, functions, and syntax of every collection class.

A nice example of this is the procedure for adding an element and a vector to a hash table.

Let's see an example here:

// why collection framework was needed

The Array, Vector, and Hash table collections had a standard member interface, which made it hard for programmers to design algorithms that could manage several types of collections. Another disadvantage is that since the majority of the 'Vector' methods are final, therefore we can't modify the 'Vector' class to create an equivalent collection. As a result, the Java development team created the Collection Framework in JDK 1.2 as a common interface to handle the aforementioned problems; this framework was used to standardize both the hash table and the outdated vectors.

Advantages of Java collection framework

Since the aforementioned disadvantages stem from the absence of a collecting framework, the following are advantages of having one.

When all classes that implement an application programming interface (API) utilize the same set of methods, that API is said to be consistent. This comprises, among other things, Set, LinkedList, Vector, and ArrayList.

reduces the developer's workload on the code by letting him focus on using the collection as efficiently as can rather than thinking about how it was designed. This successfully implements the core concept or features of object-oriented programming, which is sometimes referred to as abstraction.

Enhances the effectiveness and caliber of the program Since algorithms and data structures are supplied in a useful and efficient way—the programmer is not performing their job here—performance is enhanced. It is essential to think about how best to use a certain data structure. All he needs to do is employ the best implementation to significantly increase the efficiency of his algorithm or program.

Methods of collection interface


Collection interface

The collection interface is followed by every class that comprises the collection framework. It spells out how each set is to be done. Stated differently, a collection interface creates the basis upon which the entire framework is built.

Every subclass implements many of the methods available in the collection interface. void clean (), Boolean add All (Collection c), and Object obj are a few of these methods.

List interface

The list interface is a subset of the overall interface. These blocks allow us to store an ordered collection of items in a list-type data structure. It can hold several values in storage.

The List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack. One cannot construct the List interface without first using it.

  1. List <data-type> list1= new ArrayList();  
  2. List <data-type> list2 = new LinkedList();  
  3. List <data-type> list3 = new Vector();  
  4. List <data-type> list4 = new Stack(); 

 

Iterable interface

The primary interface via which all collection classes communicate with one another is the Iterable interface. All Aggregate subclasses implement the Iterable interface as the aggregate interface is an extension of the Iterable interface.

It has just one abstract method. in other words,

Iterator<T> iterator ()

Iterator interface

The Iterator UI provides the ability to iterate elements forward only.

Iterator UI Methods The Iterator UI has only three methods. They are: 


Array list

We can access dynamic arrays using Java thanks to the ArrayList class. It may operate more slowly than traditional arrays, but in high-traffic scenarios, it can be helpful. An ArrayList's count automatically increases as new members are added, and it automatically decreases when elements are removed. Java ArrayList allows for random access to the list. Older data types that are incompatible with ArrayList include char, int, and so on. In these cases, you need a wrapper class.

Let's understand ArrayList with the below example.

// Below Java program to show how the ArrayList works

Linked list

One technique to build the linear LinkedList data structure is with the LinkedList class. It handles each element as an individual object with data and an address component, and stores items in non-contiguous places. The parts are linked via pointers and addresses. A node is an individual component.

Let's use the following example to better understand Linked Lists.

let us try with an example:

// Below program to show the working of LinkedList in Java

Vector

In Java, we may access dynamic arrays via a vector. It may work slower than regular arrays, but it may be useful for systems that need to manipulate arrays extensively. The implementation of this is the same as that of ArrayList. But the main distinction between an array list and a vector is that the former is non-synchronized while the latter is.

Let's use an example to better grasp the Vector.

// Below program to shows the working of Vector in Java

// working of Vector

Stack

The stack data structure is implemented and modeled by the Stack class. The last-in, first-out policy governs the class. This class additionally has the empty, search, and peek methods in addition to the regular push and pop methods. Another name for the class is the Vector subclass.

Let's use an example to better grasp the stack.

// Below program to shows the working of a stack in Java

// working of a stack

Queue interface

The queue interface follows the First In First Out (FIFO) protocol, much like a real queue would. This interface can handle all of the components if the order is important. Every time we try to book a ticket, we witness this in action because there are relatively few available. As a result, the ticket will be given to the person whose request is next in line. There are several classes available, including Array-Deque and Priority-Queue. Since all of these subclasses implement Queue, if we want or need then we can use any of them to construct a Queue object.

  1. Queue<String> q1 = new PriorityQueue();  
  2. Queue<String> q2 = new ArrayDeque();

 

Priority queue

When processing items depending on their priority, a priority queue is used. The Priority-Queue class is used when processing the queue's items based on priority is necessary, even if it is widely known that the queue runs on a First-In, First-Out basis. Priority-Queue is fundamentally a priority queue. The priority queue items are sorted using either the Comparator that is specified when the queue is established or by natural order, depending on which constructor was used.

By understating the below code we can also understand the priority queue:

// priority queue in Java

Deque interface

In this instance, the Queue data structure has undergone some modification. Double queues are another type of data structure that is similar to a queue, let us add and delete bits from both ends. Compared to the queue interface, this interface is superior. The Array-Deque class makes use of this interface. We may create a deque object by implementing the Deque interface with the help of the Array-Deque class.

Deque d = new ArrayDeque();

Array deque

Array-Deque is a class that complies with the Deque specification. Deque's use is made easier by this. In contrast to a queue, we can add and remove things from both ends.

There is no size restriction for Array-Deque, and it is quicker than ArrayList and Stack.

Let’s look at the below code example.

Set interface

An array is a non-recursive set of items that prevents duplicate data from being stored. We use this collection when we wish to preserve only unique things in our collection and not any that overlap. This set interface is used by numerous classes, such as LinkedHashSet, TreeSet, HashSet, and many more. Since all of these classes implement a set, you may use any of them to create a set object.

For example.

Set<data-type> s1 = new HashSet<data-type>();  

Set<data-type> s2 = new LinkedHashSet<data-type>();  

Set<data-type> s3 = new TreeSet<data-type>();

Classes that implement the set interface

Harsh-set

The HashSet class, a private variant of the hash-table data structure, is utilized inside. It cannot be guaranteed that elements that are addable to a hash set will be added in a predetermined sequence. Every item is placed based on its hash code. Additionally, NULL objects are allowed in this class. To help you understand HashSet, consider this example.

// working of a HashSet


Sorted set interface

This interface and the fixed interface have several things in common. The only way this interface is different is that it offers additional techniques for maintaining element order. The Sorted-Set interface extends the Set interface to provide a more convenient way to handle sorted data. Without the TreeSet class, you cannot construct this interface. Since this class is an implementation of Sorted-Set, Sorted-Set instances can be created using it.

SortedSet<data-type> set = new TreeSet();

Tree set

What the TreeSet class uses is a storage tree. The array will use the elements' natural order to maintain order whether or not an explicit comparator is provided. If the set interface is incompatible with its peers, it cannot be implemented correctly. It can also be purchased with a Comparator that is meant to be delivered at a certain construction time, depending on the builder. An example will help you better understand TreeSet.

Map interface

A map is one tool for organizing data that lets you work with key-value pairs. This interface does not support duplicate keys since a single key cannot have multiple mappings. Nevertheless, duplicate values can exist for separate keys. The map comes in helpful when the data is already available and we want to use the key to conduct actions. Many classes implement this Map interface, such as HashMap, Tree-Map, and others. All of these classes implement Map, thus we can use any of them to generate a Map object.

Map<T> hm = new HashMap<> (); 

Map<T> tm = new TreeMap<> ();

 

Where T is the type of the object

Hash map

HashMap offers a basic Java implementation of the map interface. Data is stored using pair notation (key, value). To retrieve the value of a hash map, we must know its key. HashMap employs the hashing method. Hashing may be used to break up large strings into smaller ones that nonetheless represent the same string for more effective indexing and search operations. HashMap is also used internally by HashSet. Let's examine HashMap as an illustration.

Featured Post

ASSOCIATION RULE IN MACHINE LEARNING/PYTHON/ARTIFICIAL INTELLIGENCE

Association rule   Rule Evaluation Metrics Applications of Association Rule Learning Advantages of Association Rule Mining Disadvantages of ...

Popular