Java Series Part 8: MultiThreading 101

Multithreading is a programming concept in which the application can create a small unit of tasks to execute in parallel.

If you are working on a computer, it runs multiple applications and allocates processing power to them. A simple program runs in sequence and the code statements execute one by one

java.lang.Runnable is an interface that is to be implemented by a class whose instances are intended to be executed by a thread. There are two ways to start a new Thread – Subclass Thread and implement Runnable. There is no need of subclassing a Thread when a task can be done by overriding only run() method of Runnable.

Example:

package com.sarthak.concept;

public class MultithreadingRunner {

    public static void main(String[] args) {

        for(int i=0;i<=3;i++) {
            MultithreadingExample thread = new MultithreadingExample(i);
            Thread myThread = new Thread(thread);
            myThread.start();
        }

    }
}
package com.sarthak.concept;

public class MultithreadingExample implements Runnable{

    private int threadNumber;

    public MultithreadingExample(int threadNumber){
        this.threadNumber = threadNumber;
    }
    @Override
    public void run() {

            for (int i = 0; i <= 3; i++) {
                System.out.println(i + " from thread " + threadNumber);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }


    }
}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s