How to Create New Thread in Java


This example demonstrates how to create a new thread by implementing Runnable interface in Java.

Source Code

package com.beginner.examples;

public class NewThreadExample implements Runnable {
	  int count = 3;
	 
	  public NewThreadExample() {
	  }
	 
	  @Override
	  public void run() {
		  //print count
	      while (count > 0) {
	        System.out.println(Thread.currentThread().getName() + " : " + count);
	        count--;
	      }
	  }
	 
	  public static void main(String[] args) {
		 
	    NewThreadExample t = new NewThreadExample();
	    //create new thread
	    new Thread(t, "Thread1").start();
	    new Thread(t, "Thread2").start();
	  }
}

Output:

Thread1 : 3
Thread1 : 2
Thread1 : 1
Thread2 : 3
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments