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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago