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 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…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…
Build an autocomplete system that, given a query string s and a set of possible…
Design a job scheduler that accepts a function f and an integer n. The scheduler…