In this post, we will see Java Runnable example.
As you might know, there are two ways of creating threads in java.
- Extending thread class
- Implementing Runnable interface.
As you can extend only one class in java, it is not possible to extend any other class if a class extends thread class.You can also implement Runnable interface and then pass it Thread class constructor. As class can implement multiple interfaces in java, it is a good idea to create thread via implementing Runnable interface.
Java Runnable example
Create a class named SampleRunnable which will implement Runnable interface. When you implement Runnable interface, you need to provide an implementation for run method.
1 2 3 4 5 6 7 8 9 10 |
package org.arpit.java2blog; public class SampleRunnable implements Runnable{ public void run() { System.out.println("In run method"); } } |
Create Main class named "JavaRunnableMain"
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package org.arpit.java2blog; public class JavaRunnableMain { public static void main(String[] args) { Runnable runnable=new SampleRunnable(); // Pass Runnable to constructor of thread class Thread t=new Thread(runnable); t.start(); } } |
When you run above program, you will get below output
Java Anonymous Runnable example
You can also pass Runnable to Thread class by providing Anonymous Runnable implementation. You do not need to create separate class to implement run method.You can simply create Anonymous class and provide the implementation of run method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package org.arpit.java2blog; public class JavaAnoynomousRunnableMain { public static void main(String[] args) { Thread t=new Thread(new Runnable() { @Override public void run() { System.out.println("In Run method"); } }); t.start(); } } |
When you run above program, you will get below output
Java 8 Runnable example
As Runnable is the functional interface, you can simply use the lambda expression to provide implementation of Runnable interface instead of creating Anonymous Runnable as above.
1 2 3 4 5 6 7 8 9 10 11 |
package org.arpit.java2blog; public class Java8RunnableMain { public static void main(String[] args) { Thread t=new Thread(()->System.out.println("In Run method")); t.start(); } } |
When you run above program, you will get below output
That’s all about Java Runnable example.