Multithreading

In computer architecture, multithreading is the ability of a central processing unit (CPU) (or a single core in a multi-core processor) to provide multiple threads of execution concurrently, supported by the operating system. In this post, I will talk about multithreading in Java.


Creating Thread

Approach 1: Using derived thread class instance

  • Create a derived Thread class instance
  • Invoke the start() method from Thread class to start a new thread to execute the run() method
    • It is illegal to start a thread multiple times.

Define a thread class

public class MyThread extends Thread {
    @Override
    public void run() {
        // Task to execute
        for (int i = 0; i < 20; i++) {
            System.out.println("Run: " + i);
        }
    }
}

Demo

public class Demo01Thread {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        for (int i = 0; i < 20; i++) {
            System.out.println("Main: " + i);
        }
    }
}

Output

// Main: 0 Main: 1 Run: 0 Main: 2 Main: 3 Main: 4 .....