In order to create , execute and run a simple Thread in Java , we need to perform few operations . We can create a thread by two ways :
1 . First way is to create a thread by implementing Runnable Interface . Generally , Runnable Interface has one method called as run . This run method performs the logic for our thread . We have to provide implementation to this method from the Runnable Interface and execute it when we want to execute code in threads.
2 . Second way is to extend Thread class in Java and override run method .
Program to demonstrate creation and running of a Thread by implementing Runnable Interface
package com.hubberspot.multithreading.example ; // Implementing Runnable Interface class MyRunnable implements Runnable { // Implementing run method of Runnable public void run( ) { for( int i = 1 ; I < = 5 ; i++ ) System.out.println( " Message " + i ) ; } } public class RunnableTest { public static void main( String[ ] args ) { MyRunnable r = new MyRunnable( ) ; Thread t = new Thread( r ) ; System.out.println( t ) ; // starting the thread by start method which will // call run method internally t.start( ) ; } }Output of the program :