1. Introduction
In this tutorial, We'll be learning how to create a thread in java. Before going to thread creation we should understand first the basic things about processors in our devices such as laptops and mobile smartphones.
Nowadays, we can use different applications at the same time. This can be working with Microsoft word document while listening to music or playing a game online. we can do all these things because we have an operating system that supports all of these.
Apart from different applications, we can do different works in one application. For instance, eclipse we can do write program and parallel we can run a search or building the application. Because our modern programming languages support to allow running multiple threads that run different tasks.
Coming to java, A Thread can be created in two ways as below.
A) Using Thread class
B) Using Runnable interface but we need to pass the object of this class to Thread class constructor.
Thread is a from java.lang package and Runnable is from java.util package.
Before going to Thread creation, JVM will create a default thread when you start executing the Main program that has main() method. Just write a demo main program and see the name of the current execution thread using Thread.currentThread().getName() method.
package com.java.w3schools.blog.java.program.to.threads;
public class MainThread {
public static void main(String[] args) {
System.out.println("is this main thread?");
String threadName = Thread.currentThread().getName();
System.out.println("Let us see what is the current thread name: " + threadName);
}
}
Output:
is this main thread?
Let us see what is the current thread name: main
Note: JVM creates a new Thread that executes main() method and this is the first thread in concurrent and non-concurrent applications.
2) Extending Thread Class
This is very simple to create new thread objects. To make a class get threading power that class just needs to extend Thread class. Next is to create the object and call start() method.
Take a look at the below class that extends Thread class and overridden run() method implementation.
class PrintNumbersThread extends Thread {
@Override
public void run() {
IntStream.range(1, 11).forEach(n -> System.out.println(Thread.currentThread().getName() + " - " + n));
}
}
The above class prints numbers from 1 to 10 using a thread and IntStream.range() method. As well, the run() method will be printing the current execution thread name and a number.
Now, We will create two threads and all start() method to start two new threads.
package com.java.w3schools.blog.java.program.to.threads;
import java.util.stream.IntStream;
public class ThreadExtendsClass {
public static void main(String[] args) {
PrintNumbersThread numbers1 = new PrintNumbersThread();
numbers1.setName("PrintNumbers Thread 1");
numbers1.start();
PrintNumbersThread numbers2 = new PrintNumbersThread();
numbers2.setName("PrintNumbers Thread 2");
numbers2.start();
}
}
Let us see the output. Every time you run the program, you will see the different outcomes. Because we or JVM do not know who will get the chance to execute first.
Note: Here we have create two objects of PrintNumbersThread to create two new threads. See in the next section to understand more about this.
We are now seeing the second way to create threads using the Runnable interface. We have created a class PrintNumberRunnable that implements Runnable. Runnable interface has run() method and this has to be implemented by implementation class.
PrintNumbers Thread 2 - 1
PrintNumbers Thread 1 - 1
PrintNumbers Thread 2 - 2
PrintNumbers Thread 1 - 2
PrintNumbers Thread 2 - 3
PrintNumbers Thread 1 - 3
PrintNumbers Thread 2 - 4
PrintNumbers Thread 1 - 4
PrintNumbers Thread 1 - 5
PrintNumbers Thread 2 - 5
PrintNumbers Thread 1 - 6
PrintNumbers Thread 2 - 6
PrintNumbers Thread 1 - 7
PrintNumbers Thread 2 - 7
PrintNumbers Thread 1 - 8
PrintNumbers Thread 2 - 8
PrintNumbers Thread 1 - 9
PrintNumbers Thread 2 - 9
PrintNumbers Thread 1 - 10
PrintNumbers Thread 2 - 10
Note: Here we have create two objects of PrintNumbersThread to create two new threads. See in the next section to understand more about this.
3) Implementing Runnable Interface
We are now seeing the second way to create threads using the Runnable interface. We have created a class PrintNumberRunnable that implements Runnable. Runnable interface has run() method and this has to be implemented by implementation class.
package com.java.w3schools.blog.java.program.to.threads;
import java.util.stream.IntStream;
/**
*
* Runnable - Thread creation examples.
*
* @author JavaProgramTo.com
*
*/
public class ThreadImplementsRunnable {
public static void main(String[] args) {
PrintNumberRunnable numberRunnableThread = new PrintNumberRunnable();
Thread t1 = new Thread(numberRunnableThread);
t1.setName("Runnable Thread 1");
t1.start();
Thread t2 = new Thread(numberRunnableThread);
t2.setName("Runnable Thread 2");
t2.start();
}
}
Implementing Runnable Interface Example:
class PrintNumberRunnable implements Runnable {
@Override
public void run() {
IntStream.range(1, 11).forEach(n -> System.out.println(Thread.currentThread().getName() + " - " + n));
}
}
This program compiles and runs fine and produces a random output as see in thread creation using Thread class. But, here created only one object for PrintNumberRunnable class and passed the same object to two threads. This is the flexibility that comes with the Runnable Interface.
4) Thread Class VS Runnable Interface
If you see in both examples, We need to create the Thread class object but 100% the second approach implementing the Runnable interface approach is preferred by all developers.
Take a look at the following advantages over the Thread class.
A) This is straight forward. Runnable is an interface that means when a class implementing an interface that class can extend a class. Here using the Runnable interface, can allow implementing the Runnable interface and extend another class. But if we use Thread class to create a thread then we can extend only Thread class.
B) Runnable implementation class objects can be used as another powerful concurrency feature Executors. This gives you more flexibility to change your concurrent applications.
C) One Runnable object can be used with different threads.
Note: Once a Thread object is created then you must invoke the start() method to create a new thread execution that calls run() method of Thread. But, If you call directly run() method then no new Thread will be created. This is exactly equal to the normal method invocation. Freshers who are not having sufficient knowledge on threads will call run() method directly.
5. Conclusion
In this article, We've seen the methodologies for creating a thread in java. Example program on Thread class and Runnable interface.
Finally, Seen the differences between Thread creation using Thread class and Runnable Interface.
Next, read the article on how to stop a thread, Thread class stop() method is deprecated but this concept is tricky to understand.
0 Comments