Thread, Thread Pool, Thread Notify in Java

Tram Ho

Introduce

In this article, we will learn about Thread, Multi Thread, Daemon Thread, Deadlock, Life Cycle…. understand and apply thread impractical. GetGoooo…..

  • The content of the article is partially supported by ChatGPT

Define

Thread is a unique property of Java. It is the smallest unit of executable code that does a particular job. The Java language and the Java virtual machine are both threaded systems.

Multi Thread

  • Java supports multithreading, which is capable of working with multiple threads. An application can contain multiple threads
  • Multithreading keeps the idle time of the system to a minimum (ie squeeze it out =))). This allows you to write highly efficient programs with maximum CPU utilization. Each part of the program is called by a thread, each thread defining a different path of execution. This is a specialized design of multitasking.
  • In multitasking, multiple programs run concurrently, each with at least one thread in it. A microprocessor executes all programs. Although it may appear that programs are being executed concurrently, the processor is in fact jumping back and forth between processes.

The theory will be like that, let’s practice together to understand better about Thread!

Create and manage Threads

When Java programs are executed, the main thread is always being executed, it is created automatically when you start the program, sub-threads will usually be created through it, it is also a thread. the last drug of the program

To create a Thread, there are usually 2 ways

  1. Using Thread

2.Using Runnable

There are few differences when you use Runnable and Thread

  1. Runnable is an interface in Java, and Thread is a class that implements Runnable. If you want to create a new thread, you can either implement the Runnable interface or inherit from the Thread class.
  2. Runnable provides only one run() method to run a task, while Thread provides many other methods to control the flow, such as start(), interrupt(), join() and sleep().
  3. Runnable can be used in many cases, while Thread can only be used in some specific cases. Therefore, using Runnable is a better choice in case you want to run multiple threads with the same task.

Ok now let’s make a program and analyze it

image.png

Extract from the results image.png

Each thread in a Java program is registered for a priority. The Java virtual machine never changes thread precedence. The priority remains constant until the thread is interrupted.

Each thread has a priority value that ranges from Thread.MIN_PRIORITY to Thread.MAX_PRIORITY ie 1-10. Each thread depends on a thread pool, and each thread pool has its own priority usually equal to 5.

image.png Surfing the net, I found this old picture showing the life cycle of Thread.

Thread’s status

1 Thread in Java usually exists 6 states

New : Thread has been created but not run yet.

Runnable : Thread is running or waiting for CPU to be executed.

Blocked : Thread is blocked while waiting for an object to be used by another thread.

Waiting : Thread is waiting for an event to happen or another thread to send a notification to it.

Timed waiting : Thread is waiting for a certain amount of time.

Terminated : Thread has ended or was shut down carelessly.

When a thread is created, it will not run automatically, but needs to be called via the start() method.

When the sleep() method is called, it will be suspended and returned to the Waiting state

Some common functions of Thread.

getName() gets the Thread name.

isAlive() returns True if Thread still exists.

getPriority() returns Thread’s priority.

setName() sets the name for the Thread.

join() this function will wait until your Thread dies.

isDaemon() is Thread Daemon or not.

resume() marks the thread as a rare thread (Daemon).

sleep() suspends execution.

start() Calls the run() method to start a thread.

Rare Thread (Daemon Thread)

Daemon Thread aka the friendlier name and rare thread is designated as the “background” thread. Users create user threads and provide “services” to other threads.

In Java there is always at least one rare thread that is known as the “garbage collection” thread.

You can use the setDaemon method to designate a Thread as a Rare Thread.

Example Thread Notify, Simple Thread Pool

Let’s do a simple example of Thread.

In this example we will create a Thread Pool, and when the Thread completes we will fire notify to notify.

Ok! Let’s start….

In order for Thread to be able to register Listeners, I will create a new Thread that implements from Runnable

Create the ThreadCompleteListener interface for the Listeners to re-implement.

Create a class to manage Thread

  • VoidSupplier is also a similar FunctionalInterface from Supplier.

Ok, let’s test it now.

where ClassRunThread is the class they want to run in the new Thread, ClassReceiveNotify implements ThreadCompleteListener to receive notifications.

Screenshot 2023-02-05 at 21.37.29.png

and this is the result we get.

A little more advanced, let’s create a Pool for it to manage the amount of Thread created.

In the above class I will save the number of Threads running in the currentThread, I consider the ThreadPool as a Listener to receive notifications when the Thread completes and adjust the currentThread.

In the above example, I use the sleep function to suspend 100ms when currentThread > maxThread. (There will be many other ways for you to do it, for example, put in Queue…. in this simple example, I will sleep quickly =)) )

Ok! Next, I will create another Builder for it to be professional

Now let’s see the results.

I created a ThreadPool with a max of 2, but I run 4 Threads at the same time and the picture below is the result

Screenshot 2023-02-05 at 21.55.09.png

As you can see process 1 and process 2 are processed at the same time, while process 3 and process 4 need to wait because Pool size only allows 2.

Conclude

In this article, I have gone through the theory of Thread, made a simple example of Thread that I have drawn from real projects and simplified it for you to understand.

Thank you for watching the article, if there are any mistakes in the content, I hope to receive comments from everyone

Share the news now

Source : Viblo