coderz.py

Keep Coding Keep Cheering!

Creating a Thread in Java

java thread class

A thread can be created in one of two ways:

  • By extending the Thread class
  • By implementing Runnable interface.

Implementing the runnable interface and overriding the run() method allows you to create threads. The start() method can then be called after creating a thread object.

Thread class:

Constructors and methods for starting and managing threads are available in the Thread class. The thread implements the Runnable interface and extends the Object.

Runnable interface:

The Runnable interface should be implemented by all classes that have instances that are meant to be executed by threads. The Runnable interface has only one method, which is called run().

Example: By using Thread Class
import java.io.*;
class Coderz extends Thread {
	public void run()
	{
		System.out.print("Thread run by coderzpy.");
	}
	public static void main(String[] args)
	{
		Coderz g = new Coderz(); // creating thread
		g.start(); // starting thread
	}
}
Output:
Thread run by coderzpy.
Example: By implementing Runnable interface
import java.io.*;
class coderz implements Runnable {
	public static void main(String args[])
	{
		// create an object of Runnable target
		coderz obj = new coderz();

		// pass the runnable reference to Thread
		Thread t = new Thread(obj, "obj");

		// start the thread
		t.start();

		// get the name of the thread
		System.out.println(t.getName());
	}
	@Override public void run()
	{
		System.out.println("Inside run method");
	}
}
Output:
obj
Inside run method
Thread creation advantages:
  • Java Threads are more lightweight when compared to processes; creating a thread requires less time and resources.
  • Data and code from a thread’s parent process are shared.
  • Process communication is more complicated than thread communication.
  • Changing between processes is typically more expensive than changing between threads.

Note: also read about the Java Thread Class

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Comment

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

Advertisement