A thread can be created in one of two ways:
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.
Constructors and methods for starting and managing threads are available in the Thread class. The thread implements the Runnable interface and extends the Object.
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().
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
}
}
Thread run by coderzpy.
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");
}
}
obj
Inside run method
Note: also read about the Java Thread Class
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
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…