Java Create Multiple Threads Example



Java Thread Examples


In this example, we create 2 threads, you can create any number of threads that required to satisfy your requirement.

Java Create Multiple Threads Example

Here is the complete example of creating multiple threads in Java:
public class ThreadSleepExample {
    public static void main(final String[] args) {
        System.out.println("Thread main started");
        final Thread thread1 = new Thread(new WorkerThread());
        thread1.setName("WorkerThread 1");
        final Thread thread2 = new Thread(new WorkerThread());
        thread1.setName("WorkerThread 2");
        thread1.start();
        thread2.start();
        System.out.println("Thread main ended");
    }
}

class WorkerThread implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
        try {
             Thread.sleep(1000);
             System.out.println("[" + Thread.currentThread().getName() + "] Message " + i);
        } catch (final InterruptedException e) {
             e.printStackTrace();
        }
     }
  }
}
Output:
[WorkerThread 2] Message 0
[Thread-1] Message 0
[Thread-1] Message 1
[WorkerThread 2] Message 1
[WorkerThread 2] Message 2
[Thread-1] Message 2
[WorkerThread 2] Message 3
[Thread-1] Message 3
[Thread-1] Message 4
[WorkerThread 2] Message 4

Comments