Java provides two ways to create a thread programmatically.
In the previous example, we have seen Java Create Thread using Runnable Interface Example.
In this example, we will learn how to create a thread using a Thread class.
Let's create a new thread simply by extending your class from java.lang.Thread and overriding it’s run() method.
The run() method contains the code that is executed inside the new thread. Once a thread is created, you can start it by calling the start() method.
Let's demonstrate how to create and start a Thread by extending java.lang.Thread class.
In this example the main() method is the main thread, we will create and start the WorkerThread in the main thread.
class WorkerThread extends Thread {
private String anyData;
public WorkerThread(final String anyData) {
this.anyData = anyData;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("[" + Thread.currentThread().getName() + "] "
+ "[data=" + this.anyData + "] Message " + i);
try {
Thread.sleep(200);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* Instantiate a thread by using Thread class.
* @author Ramesh fadatare
**/
public class ThreadExample {
public static void main(final String[] args) {
System.out.println("Thread main started");
final Thread thread = new WorkerThread("Process data using WorkerThread");
thread.start();
thread.setName("WorkerThread");
System.out.println("Thread main finished");
}
}
Output:
Thread main started
Thread main finished
[WorkerThread] [data=Process data using WorkerThread] Message 0
[WorkerThread] [data=Process data using WorkerThread] Message 1
[WorkerThread] [data=Process data using WorkerThread] Message 2
[WorkerThread] [data=Process data using WorkerThread] Message 3
[WorkerThread] [data=Process data using WorkerThread] Message 4
Comments
Post a Comment