Java Threading - Introduction to Multi-Threading


A thread is a path of execution that exists within a process.

One process may have one or more threads.

A Single-threaded process has one thread while a multi-threaded process has more than one threads.

In the single-threaded process, we have only one flow of execution of instructions while in multi-threaded process we have we have multiple sets of instructions executed simultaneously.

A multi-threaded process has parts running concurrently and each part can do a given task independently.

So multi-threadig is a mechanism that allows us write programs in a way in which multiple activities can proceed concurrently in the same program.

But, it is also important to note that in reality, a system that has only a single execution core can create the illusion of concurrent execution. It does this by executing the various threads in an interleaved manner. But it does it fast such that we think that it's actually doing tasks concurrently.

Threads - Flow of Execution

A thread is a flow of execution in a process.

Any program atleast has one thread of execution in its process. As per our needs, we are free to create additional flows of execution.

This allows us perform tasks concurrently. Concurrent applications are applications that utilize concurrent flows of execution or multiple threads.

If the application is running on a single core processor and you've written concurrent code, the tasks will get multiplexed.

This implies that the processor will very quickly be switching between the context of each of our threads. So to us the tasks will all be happeining at the same time.

But in reality, and to the processor, only one task, and one thread will be running at any given instance.

However, on a multicore processor,more than one thread can run at a given time.

Why Concurrency and Multi-Threading?

For two reasons:

  1. Make applications responsive
  2. Make them faster.

Every program, we had said earlier has atleast one thread of execution.

This is normally called the main thread or the current thread.

This thread, when we start our application, starts executing tasks sequentially. Reasonably, those tasks need to be able to finish faster so that other tasks can also be performed at the required time.

And in a case that the tasks take only a fraction of a second, the single thread will be more than adequate.

However, nowadays applications are complex and involve fetching data from third party sources and making complex processing and alot of disk writing.

When these are happening, the user cannot interact with the application as for instance, the data is being downloaded, so users cannot even click a button. If it takes minutes or hours, they'll have to wait. That is if your application is single threaded.

Obviously that's not what users expect and it would definitely more than a terrible experience. So the solution is to assign these tasks into background thread.

The the user can continue using the application as the background task takes place. After all, Operating Systems have the ability to quickly switch through tasks thus making efficient use of the processor, even if it is one.

The Main Thread

After you've written your program, compiled it and run it, one thread will be created and associated to the program's main() method.

The thread will execute the statements you'd written in the main() method one after the other.

The main() method is normally the entry point to all java applications. So the thread associated with it is normally called the main thread.

This thread, the main thread, is never created by us explicitly. However, we can manipulate some of its properties.

To do that we need a reference of the Thread class corresponding to that main thread.

So we can use the static currentThread() method defined in the Thread class.

The currentThread() method will return a reference to the currently executing thread object.

Thread myThread = Thread.currentThread();

If we call this in the main() method we will get a reference to the main thread.

public class MrMain {

    public static void main(String[] args) {
        Thread mainThread=Thread.currentThread();
        System.out.println("Current Thread: "+mainThread);
        System.out.println("Current Thread Name: "+mainThread.getName());
        System.out.println("Current Thread ID: "+mainThread.getId());
        System.out.println("Current Thread Priority: "+mainThread.getPriority());
        System.out.println("Current Thread State: "+mainThread.getState());
        System.out.println("------------------------------");

        System.out.println("Change Thread name and Priority.");
        mainThread.setName("EngineThread");
        mainThread.setPriority(7);
        System.out.println("------------------------------");

        System.out.println("After the Changes.");
        System.out.println("Current Thread: "+mainThread);
        System.out.println("Current Thread Name: "+mainThread.getName());
        System.out.println("Current Thread Priority: "+mainThread.getPriority());

    }
}

Result

Current Thread: Thread[main,5,main]
Current Thread Name: main
Current Thread ID: 1
Current Thread Priority: 5
Current Thread State: RUNNABLE
------------------------------
Change Thread name and Priority.
------------------------------
After the Changes.
Current Thread: Thread[EngineThread,7,main]
Current Thread Name: EngineThread
Current Thread Priority: 7

We've printed the thread's name,id,priority and state above.Then modified the name and priority as they are modifiable.

This line Current Thread: Thread[main,5,main] tells us the thread's name,it's priority and the thread group's name.

Whenever a thread is created, a name is automatically generated for it and assigned to it. The name is used to identify the thread.

This name can be changed by explicitly. In fact multiple threads can share the same name since the name is just a string.

Best Regards.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post