In Java Thread Example, Creating threads in Java is simple. Threads are implemented in the form of objects that contain a method called run(). The run() method is the heart and soul of any thread. It makes up the entire body of the thread and is the only method in which the thread’s behavior can be implemented.
public void run()
……….. (statements for implementing thread)
The run() method should be invoked by an object of the concerned thread. This can be achieved by creating the thread and initiating it with the help of another thread method called start().
A new thread can be created in two ways.
By creating a thread class: Define a class that extends Thread class and override its run() method with the code required by the thread.
By converting a class to a thread: Define a class that implements Runnable interface. The Runnable interface has only one method, run (), that is to be defined in the method with the code to be executed by the thread.
Thread Class Methods :
Some commonly used methods of Thread class are given below:
currentThread() : Returns reference to the currently executing thread object.
getName() : Returns the name of the thread in which it is called.
getPriority() : Returns the Thread’s priority
interrupt() : Used for Interrupting the thread.
interrupted() : Used to check whether the current thread has been interrupted or not.
isAlive() : Used for testing whether a thread is alive or not.
setName() : Changes the name of the thread to NewName.
setPriority() : Changes the priority of thread.
sleep() : Causes the currently executing thread to sleep for the specified number of microsecond.
10 start() : Used to begin execution of thread. The java virtual machine calls the run method of the thread in which this method is called.
toString() : Returns a string represntation of thread.
yield() : Used to pause temprarily to currently executing thread object and allow other threads to execute.
activeCount() : Returns the number of active threads in the current thread’s thread group.
destroy() : Destroys the thread without any cleanup.
Java Thread Example :
class MyThread implements Runnable
private char c;
private int times;
public MyThread(char x, int n)
c = x;
times = n;
public void run()
for(int i = 1; i<= times; i++)
System.out.println(c + ” character is ” + i + ” times….”);