Ways of creating threads in Java
In this post I will tell you about how to create threads in Java. So, let's get started!
Threads in Java are objects. They are instances of java.lang.Thread class or its subclasses.
There are two ways of creating threads in Java:
First. We can just create an instance of Thread class.
Thread thread = new Thread();
// And start it
thread.start();
But this is useless, because our thread has no code to execute. Instead we can extend Thread class and create our subclass of Thread with custom code to execute.
public class CustomThread extends Thread {
public void run(){
System.out.println("Our custom thread is running");
}
}
CustomThread customThread = new CustomThread();
customThread.start();
In method run we can put all necessary code to execute in our thread.
Also we can create anonymous subclass of Thread class.
Thread thread = new Thread(){
public void run(){
System.out.println("This is anonymous subclass of Thread. And its running now!");
}
}
thread.start();
Second. We can implement Runnable interface.
We will create class that implements the java.lang.Runnable interface. That interface has only one method - run:
public interface Runnable() {
public void run();
}
There are three variants of implementing Runnable interface:
-
We can create a typical class that implements the Runnable.
public class CustomRunnable implements Runnable { public void run(){ System.out.println("CustomRunnable is running now"); } }
-
We can create an anonymous class that implements the Runnable.
Runnable customRunnable = new Runnable(){ public void run(){ System.out.println("Runnable is running now"); } }
-
We can create lambda that implements the Runnable.
Runnable runnable = () -> { System.out.println("Lambda Runnable is running now"); };
That's all. Will be glad if you find this post useful.
Comments
Post a Comment