Creating And Running A Thread Using Runnable Interface

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( ) ;
}
}

 


For more of such hot topics read my other posts here :

Visit my new website



Article Written By jontymagicman

I am DInesh Varyani.

Last updated on 26-07-2016 267 0

Please login to comment on this post.
There are no comments yet.
How To Create A Simple Frame Using Swing Api In Java?.
How To Use Java.net.inetaddress Class For Java Networking ?.