Java - Create Multiple Threads

Introduction

Java does not have any upper limit on the number of threads that can be used in a program.

It is limited by the operating system and the memory available.

The following code creates two threads. Both threads print integers from 1 to 5.

Demo

public class Main {
  public static void main(String[] args) {
    // Create two Thread objects
    Thread t1 = new Thread(Main::print);
    Thread t2 = new Thread(Main::print);

    // Start both threads
    t1.start();//ww  w  .ja  v  a  2 s. c  o m
    t2.start();
  }

  public static void print() {
    for (int i = 1; i <= 5; i++) {
      System.out.println(i);
    }
  }
}

Result

Note

The code starts the thread t1 first and the thread t2 second.

start() method of the Thread class returns immediately.

JVM does not start the thread right away.

When a thread starts, it is up to the operating system to decide when and how much CPU time is given to that thread.

As soon as the t1.start() and t2.start() methods return, your program enters the indeterminate state.

Both threads will start running but you do not know when they will start running and in what sequence.

Related Topic