Multithreading in Java

What is a thread?

It is a unit of a process.

Example:
Let use take a scenario where multiplying an array of a thousand numbers with 2. If each operation takes 1 second, it would take a 1000 seconds to complete the whole task.

With the help of threads, we can cut the time significantly. Threads allow a program to be run concurrently working on different process at the same time. This concept is called Multithreading.

How to create a thread and perform multithreading?

  1. Create a class that specifies the task that must be accomplished
  2. Everything has the method called run and run is responsible for the task that must be accomplished.
  3. To use a thread, the class must extend thread
  4. Then make an instance of the thread by declaring the following
    1. Thread threadObject = new ThreadClassName();
    2. threadObject.run();
      1. run() will execute one thread
  5. start() will automatically call the run method and achieve parallel processing or multithreading.

Why use the runnable interface?

Runnable does the same as the thread class but using an interface, another class can be extended which is not possible when extending the thread class. This is due to the fact that java doesn’t allow extension of more than one class.

Leave a comment

Design a site like this with WordPress.com
Get started