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.
You are given two singly linked lists that intersect at some node. Your task is…
A builder plans to construct N houses in a row, where each house can be…
Find the length of the longest absolute path to a file within the abstracted file…
You manage an e-commerce website and need to keep track of the last N order…
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…