How to create Thread in Java

There are two standard ways to create a thread. One is using thread class and other is by using Runnable.


Create Thread using Thread class


Thread thread1 = new Thread() {
public void run() {
for (int i=0; i<100; i++) {
System.out.println("Line " + i);
}
}
};
thread1.start();

Create Thread using Thread class


Runnable runnable = new Runnable() {
public void run() {
for (int i=0; i<100; i++) {
System.out.println("Line " + i);
}
}
};
Thread thread2 = new Thread(runnable);
thread2.start();

Another way to create a thread is as follows
“new Thread(new Runnable(){public void run(){}}).start();”

Here we use the ‘new Thread(Runnable runnable)‘ constructor to create a Thread:

Thread thread = new Thread(new Runnable() {
public void run() {
// Do something
}
}
);
thread.start();

The Runnable interface is another way in which you can implement multi-threading other than extending the Thread class due to the fact that Java allows you to extend only one class.

Runnable is often used to provide the code that a thread should run, but Runnable itself has nothing to do with threads. It’s just an object with a run() method.

References: stackoverflow.com

Leave a Reply

Your email address will not be published. Required fields are marked *