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

Select a Random Element from a Stream

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

1 day ago

Estimate π Using Monte Carlo Method

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

3 weeks ago

Longest Substring with K Distinct Characters

Given an integer k and a string s, write a function to determine the length…

3 weeks ago

Staircase Climbing Ways

There is a staircase with N steps, and you can ascend either 1 step or…

4 weeks ago

Autocomplete System Implementation

Build an autocomplete system that, given a query string s and a set of possible…

4 weeks ago

Job Scheduler Implementation

Design a job scheduler that accepts a function f and an integer n. The scheduler…

4 weeks ago