Categories: Java

Creating a Thread in Java

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

Share
Published by
Rabecca Fatima

Recent Posts

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

20 hours ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

3 days ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

3 weeks ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

1 month ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

1 month ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

2 months ago