All About Class Thread in Java

Concept of Concept switching

Context switching is a term defined for the operating systems when multiple processes share a single processor, the operating system, in order to process another request, must stop the current process and assign it to another process.

It executes a sequence of events called a context switch to transfer control from one process to another. During this process, the operating system has to save a lot of information and need to load a lot of information for the upcoming process.

Context switching involves thousands of machine instructions. During multiple thread execution, context switching is provided by java itself.

The Thread class encapsulates all of the information about a single thread of control running in a Java environment. Thread objects are used to control threads in a multithreaded program.

The execution of Java code is always under the control of a Thread object. The Thread class provides a static method called currentThread() that can be used to get a reference to the Thread object that controls the current thread of execution.

In order for a Thread object to be useful, it must be associated with a method that it is supposed to run.

Java provides two ways of associating a Thread object with a method:
Declare a subclass of Thread that defines a run() method. When such a class is instantiated and the object’s start() method is called, the thread invokes this run() method.

Pass a reference to an object that implements the Runnable interface to a Thread constructor. When the start() method of such a Thread object is called, the thread invokes the run()method of the Runnable object.

After a thread is started, it dies when one of the following things happens:
The run() method called by the Thread returns.An exception is thrown that causes the run() method to be exited.The stop() method of the Thread is called.

Thread in Java

A thread in java is a flow of control within a program. It is similar to process except for multiple threads within the same application share much of the same state. They run in the same address space. It means that threads share instance variables but not local variables.

Java provides two ways of associating a Thread object with a method:

  • Declare a subclass of Thread that defines a run() method. When such a class is instantiated and the object’s start() method is called, the thread invokes this run() method.
  • Pass a reference to an object that implements the Runnable interface to a Thread constructor. When the start() method of such a Thread object is called, the thread invokes the run()method of the Runnable object.

Thread class allows us to run multiple programs at a time. A Thread corresponds to the control of the program. Every Thread has its own priority. Threads with higher priority are executed first than the lower priority Threads. Each thread may or may not be marked as Daemon Thread.
During execution, a Thread creates another child Thread, the child Thread will have the same priority as parent Thread. Similarly, if a Daemon Thread creates a child thread, it will be automatically Daemon Thread. When java virtual machine continues to execute, there is usually a single Thread(on Daemon) which calls the main method of some class. The JVM continues to execute threads until one of the following occurs:

  1. The exit() method of class Runtime has been called and the Security Manager has permitted the exit operation.
  2. All Threads that are not Daemon Threads have died either by run time from the call to the run() method or by performing the stop() method.

If several threads are trying to access the same variable without some kind of coordination, we may get the wrong result. To avoid this a thread can reserve the right to use an object until it is finished it’s a task. A thread if important can raise its priority.

Thread class encapsulates all the information about a single thread of control running on the Java interpreter. To create a thread, we must pass a Runnable object (i. e., an object that implements the Runnable interface by defining a run() method) to the Thread constructor, or we must subclass Thread so that it defines its own run() method.

The run() method of the Thread or of the specified Runnable object is the “body” of the thread. It begins executing when the start() method of the Thread object is called. The thread runs until the run() method returns or until the stop() method of its Thread object is called. The static methods of this class operate on the currently running thread. The instance methods may be called from one thread to operate on a different thread.

start() starts a thread running, stop() stops it by throwing a ThreadDeath error. Suspend() temporarily halts a thread. resume() allows it to resume, sleep() makes the current thread stop for a specified amount of time. yield() makes the current thread give up control to any other threads of equal priority that are waiting to run. join() waits for a thread to die. interrupt() wakes up awaiting or sleeping thread (with an InterruptedException) or sets an “interrupted” flag on a non-sleeping thread.

A thread can test its own “interrupted” flag with interrupted() or can test the flag of another thread with isInterrupted(). The objectWait() method makes the current thread block until the objects notify() method is called by another thread.

After a thread is started, it dies when one of the following things happens:

  • The run() method called by the Thread returns.
  • An exception is thrown that causes the run() method to be exited.
  • The stop() method of the Thread is called.

The Structure of the Thread class is given below:


public class java.lang.Thread extends java.lang.Object implements java.lang.Runnable{
//Member Elements
public final static int MAX_PRIORITY; // Max priority of a Thread is 10
public final static int MIN_PRIORITY; // Min priority of a Thread is 0
public final static int NORM_PRIORITY; // NORM priority of a Thread is 5
//Constructors
public Thread();
//Creates and allocates a new Thread object.This constructor is same as Thread(null,null,gName), where gName
//is newly generated name. This is automatic assignment in the form of "Thread-"+n where n is an integer.
public Thread(Runnable target);
//Creates and allocates a new Thread object.This constructor is same as Thread(null,null,gName), where gName 
//is newly generated name. This is automatic assignment in the form of "Thread-"+n where n is an integer.
//target is the object whose run() method is called.
public Thread(Runnable target,String name);
//Creates and allocates a new Thread object.This constructor has the same effect as Thread(null,target,name). 
//target is the object whose run() method is called. and name is the name of the Thread.
public Thread(String name);
//Creates and allocates a new Thread object whose name is specified in the argument. It is same as 
//Thread(null,null,name).
public Thread(ThraedGroup group,Runnable target);
//Creates and allocates a new Thread object.This constructor has the same functionality as 
//Thread(group,target,gName),where gName is newly generated name. This is automatic assignment in the form 
//of "Thread-"+n where n is an integer. This constructor can throw an SecurityException if the current thread 
//can not create a thread in the specified group.
public Thread(ThraedGroup group,Runnable target,String name);
//Creates and allocates a new Thread object.target is the it's run object and name as name specified in the 
//argument.It belong to the ThreadGroup referred by group.If the group is null,the new process belongs to the 
//same group as the Thread(which is creating the new Thread).If the target argument is not null,the run method 
//of the target is called when this Thread is started.If the target method is null, the Thread which is creating 
//this Thread,its run method gets executed. The priority of the newly created Thread is set equals to the priority
//of the Thread creating the new Thread.setPriority() mthod can be used to change the priority.This constructor
// can throw an SecurityException if the current thread
//can not create a thread in the specified group.
public Thread(ThraedGroup group,String name);
//Creates and allocates a new Thread object.. It has the same effect as Thread(group,null,name).
//This constructor can throw an SecurityException if the current thread 
//can not create a thread in the specified group.
//Methods:
public static int activeCount();
public static int enumerate(Thread toArray[]);
public void checkAccess();
public void destroy();
public static boolean interrupted();
public void run();
public synchronized native void start();
public final void join() throws InterruptedException;
public final synchronized void join(long millis) throws InterruptedException;
public final synchronized void join(long millis,int nanos) throws InterruptedException;
public final void resume();
public final void setDaemon(boolean on);
public final void setName(String name);
//Assigns a name of the thread as name for a thread before the exution of that thread.This enables us to identify 
//the thread with a name.This is //helpful for debugging multithreaded application.
public final void setPriority(int newPriority);
//This method sets the thread's priority value with the argument passed.
public final void stop();
public final synchronized void stop(Throwable obj);
public final void suspend();
public native int countStackFrames();
public static native Thread currentThread();
//It is a static method that returns the Thread object which is the currently running thread.
public static void dumpStack();
public static boolean interrupted();
public static native void sleep(long millis) throws InterruptedException;
public static void sleep(long millis,int nanos) throws InterruptedException;
public static native void yield();
public final String getName();
//This function returns the current String value of the thread's name as set by the method setName()
public final int getPriority();
//Returns the thread's current priority
public final ThreadGroup getThreadGroup();
public final native  boolean isAlive();
public final boolean isDaemon();
//return's true if the thread is a daemon thread, else returns false.
public boolean isInterrupted();
public String toString();
}

The details of the Thread class is given as:

public final static int MAX_PRIORITY;

public final static int MAX_PRIORITY describes the highest priority a thread can have.

public final static int MIN_PRIORITY;

public final static int MIN_PRIORITY describes the lowest priority a thread can have.

public final static int NORM_PRIORITY;

public final static int NORM_PRIORITY describes the default priority assigned to a thread.

public Thread();

public Thread() constructor creates a Thread object that belongs to the same ThreadGroup object as the current thread, has the same daemon attribute as the current thread, has the same priority as the current thread, and has a default name.

A Thread object created with this constructor invokes its own run() method when the Thread
object’s start() method is called. This is not useful unless the object belongs to a subclass of
the Thread class that overrides the run() method.

Calling this constructor is equivalent to:
Thread(null, null, genName) where genName is an automatically generated name of the form “Thread-“+n, where n is an integer incremented each time a Thread object is created.

public Thread(Runnable target);

public Thread(Runnable target) method
This method returns
Parameter

public Thread(Runnable target, String name);

public Thread(Runnable target, String name) method
This method returns
Parameter

public Thread(String name);

public Thread(String name) constructor creates a Thread object that belongs to the same ThreadGroup object as the current thread, has the same daemon attribute as the current thread, has the same priority as the current thread, and has the specified name.

A Thread object created with this constructor invokes its own run() method when the Thread
object’s start() method is called. This is not useful unless the object belongs to a subclass of the Thread class that overrides the run() method.

Calling this constructor is equivalent to:
Thread(null, null, name)

The uniqueness of the specified Thread object’s name is not checked, which may be a problem for programs that attempt to identify Thread objects by their name.

Parameter
name – The name of this Thread object.

public Thread(ThreadGroup group, Runnable target);

public Thread(ThreadGroup group, Runnable target) constructor creates a Thread object that belongs to the specified ThreadGroup object, has the same daemon attribute as the current thread, has the same priority as the current thread, and has a default name.

A Thread object created with this constructor invokes the run() method of the specified Runnable object when the Thread object’s start() method is called.

Calling this constructor is equivalent to:

Thread(group, target, genName)

genName is an automatically generated name of the form “Thread-“+n, where n is an integer
that is incremented each time a Thread object is created.
Parameter
group – The ThreadGroup object that this Thread object is to be added to.
target – A reference to an object that implements the Runnable interface.

public Thread(ThreadGroup group, Runnable target, String name);

public Thread(ThreadGroup group, Runnable target, String name) constructor Creates a Thread object that belongs to the specified ThreadGroup object, has the same daemon attribute as the current thread, has the same priority as the current thread, and has the specified name.

A Thread object created with this constructor invokes the run() method of the specified
Runnable object when the Thread object’s start() method is called.

The uniqueness of the specified Thread object’s name is not checked, which may be a problem for programs that attempt to identify Thread objects by their names.
Parameter
group – The ThreadGroup object that this Thread object is to be added to.
target -A reference to an object that implements the Runnable interface.
name – The name of this Thread object.

public Thread(ThreadGroup group, String name);

public Thread(ThreadGroup group, String name) constructor creates a Thread object that belongs to the specified ThreadGroup object, has the same daemon attribute as the current thread, has the same priority as the current thread, and has the specified name.

A Thread object created with this constructor invokes its own run() method when the Thread
object’s start() method is called. This is not useful unless the object belongs to a subclass of
the Thread class that overrides the run() method. Calling this constructor is equivalent to:

Thread(group, null, name)

The uniqueness of the specified Thread object’s name is not checked, which may be a problem for programs that attempt to identify Thread objects by their name.

Parameter
group – The ThreadGroup object that this Thread object is to be added to.
name – The name of this Thread object.

public static int activeCount();

public static int activeCount() method returns the number of threads in the ThreadGroup of the currently running thread for which the isAlive() method returns true.
This method returns the current number of threads in the ThreadGroup of the currently running thread.

public static native Thread currentThread();

public static native Thread currentThread() method returns a reference to the Thread object that controls the currently executing thread.
This method returns a reference to the Thread object that controls the currently executing thread.

public static void dumpStack();

public static void dumpStack() method outputs a stack trace of the currently running thread.

public static int enumerate(Thread tarray[]);

public static int enumerate(Thread tarray[]) method stores a reference in the array for each of the Thread objects in the ThreadGroup of the currently running thread for which the isAlive() method returns true.

Calling this method is equivalent to:

currentThread().getThreadGroup().enumerate(tarray);

If the array is not big enough to contain references to all the Thread objects, only as many
references as will fit are put into the array. No indication is given that some Thread objects were left out, so it is a good idea to call activeCount() before calling this method, to get an idea of how large to make the array.

This method returns the number of Thread objects stored in the array.
Parameter
tarray -A reference to an array of Thread objects.

public static boolean interrupted();

public static boolean interrupted() method determines whether or not the currently running thread has been interrupted.
This method returns true if the currently running thread has been interrupted; otherwise false.

public static native void sleep(long millis);

public static native void sleep(long millis) method causes the currently running thread to sleep. The method does not return until at least the specified number of milliseconds has elapsed.

While a thread is sleeping, it retains ownership of all locks. The Object class defines a method
called wait() that is similar to sleep() but causes the currently running thread to temporarily
relinquish its locks.

Parameter
millis – The number of milliseconds that the currently running thread should sleep.

public static void sleep(long millis, int nanos);

public static void sleep(long millis, int nanos) method causes the currently running thread to sleep. The method does not return until at least the specified number of milliseconds have elapsed.

While a thread is sleeping, it retains ownership of all locks. The Object class defines a method
called wait() that is similar to sleep() but causes the currently running thread to temporarily
relinquish its locks.

Parameter
millis – The number of milliseconds that the currently running thread should sleep.
nanos – An additional number of nanoseconds to sleep.

public static native void yield();

public static native void yield() method causes the currently running thread to yield control of the processor so that another thread can be scheduled.

public void checkAccess();

public void checkAccess() method determines if the currently running thread has permission to modify this Thread object.

public native int countStackFrames();

public native int countStackFrames() method returns the number of pending method invocations on this thread’s stack.
This method returns the number of pending method invocations on this thread’s stack.

public void destroy();

public void destroy() method terminates this thread without any of the usual cleanup (i.e., any locks held by the thread are not released).

This method provides a last-resort way to terminate a thread. While a thread can defeat its stop() method by catching objects thrown from it, there is nothing that a thread can do to stop itself from being destroyed.

public final String getName();

public final String getName() method returns the name of this Thread object.
This method returns the name of this thread.

public final int getPriority();

public final int getPriority() method returns the priority of this Thread object.
This method returns the priority of this thread.

public final ThreadGroup getThreadGroup();

public final ThreadGroup getThreadGroup() method returns a reference to the ThreadGroup that this Thread object belongs to.
This method returns the ThreadGroup of this thread.

public void interrupt();

public void interrupt() method interrupts this Thread object.

public final native boolean isAlive();

public final native boolean isAlive() method determines whether or not this Thread object is alive. A Thread object is alive if it has been started and has not yet died. In other words, it has been scheduled to run before and can still be scheduled to run again. A thread is generally alive after its start() method is called and until its stop() method is called.

This method returns true if this thread is alive; otherwise false.

public final boolean isDaemon();

public final boolean isDaemon() method determines whether or not this thread is a daemon thread, based on the value of the daemon attribute of this Thread object.

This method returns true if the thread is a daemon thread; otherwise false.

public boolean isInterrupted();

public boolean isInterrupted() method determines whether or not this Thread object has been interrupted.
This method returns true if this thread has been interrupted; otherwise false.

public final void join();

public final void join() method allows the thread that calls it to wait for the Thread associated with this method to die. The method returns when the Thread dies. If this thread is already dead, then this method returns immediately.

public final synchronized void join(long millis);

public final synchronized void join(long millis) method causes a thread to wait to die. The method returns when this Thread object dies or after the specified number of milliseconds has elapsed, whichever comes first. However, if the specified number of milliseconds is zero, the method will wait forever for this thread to die. If this thread is already dead, the method returns immediately.
Parameter
millis -The maximum number of milliseconds to wait for this thread to die.

public final synchronized void join(long millis, int nanos);

public final synchronized void join(long millis, int nanos) method causes a thread to wait to die. The method returns when this Thread object dies or after the specified amount of time has elapsed, whichever comes first. However, if millis and nanos are zero, the method will wait forever for this thread to die. If this thread is already dead, the method returns immediately.
Parameter
millis – The maximum number of milliseconds to wait for this thread to die.
nanos – An additional number of nanoseconds to wait.

public final void resume();

public final void resume() method resumes a suspended thread. The method causes this Thread object to once again be eligible to be run. Calling this method for a thread that is not suspended has no effect.

public void run();

public void run() method causes the thread to invoke a run() method. If this Thread object was created without a specified Runnable object, the Thread object’s own run() method is executed. This behavior is only useful in a subclass of Thread that overrides this run() method, since the run() method of the Thread class does not do anything.

public final void setDaemon(boolean on);

public final void setDaemon(boolean on) method sets the daemon attribute of this Thread object to the given value. This method must be called before the thread is started. If a thread dies and there are no other threads except daemon threads alive, the Java virtual machine stops.
Parameter
on – The new value for this thread’s daemon attribute.

public final void setName(String name);

public final void setName(String name) method sets the name of this Thread object to the given value. The uniqueness of the specified Thread object’s name is not checked, which may be a problem for programs that attempt to identify Thread objects by their name.

Parameter
name – The new name for this thread.

public final void setPriority(int newPriority);

public final void setPriority(int newPriority) method sets the priority of this Thread to the given value.
Parameter
newPriority – The new priority for this thread.

public synchronized native void start();

public synchronized native void start() method starts this Thread object, allowing it to be scheduled for execution. The top-level code that is executed by the thread is the run() method of the Runnable object specified in the constructor that was used to create this object. If no such object was specified, the top-level code executed by the thread is this object’s run() method.

It is not permitted to start a thread more than once.

public final void stop();

public final void stop() method causes this Thread object to stop executing by throwing a ThreadDeath object. The object is thrown in this thread, even if the method is called from a different thread. This thread is forced to stop whatever it is doing and throw a newly created ThreadDeath object. If this thread was suspended, it is resumed; if it was sleeping, it is awakened. Normally, we should not catch ThreadDeath objects in a try statement. If we need to catch ThreadDeath objects to detect a Thread is about to die, the try statement that catches ThreadDeath objects should rethrow them.

When an object is thrown out of the run() method associated with a Thread, the uncaughtException() method of the ThreadGroup for that Thread is called. The uncaughtException() method normally outputs a stack trace. However, uncaughtException() treats a ThreadDeath object as a special case by not outputting a stack trace. When the uncaughtException() method returns, the thread is dead. The thread is never scheduled to run again.

If this Thread object’s stop() method is called before this thread is started, the ThreadDeath object is thrown as soon as the thread is started.

public final synchronized void stop(Throwable o);

public final synchronized void stop(Throwable o) method causes this Thread object to stop executing by throwing the given object. Normally, the stop() method that takes no arguments and throws a ThreadDeath object should be called instead of this method. However, if it is necessary to stop a thread by throwing some other type of object, this method can be used.

The object is thrown in this thread, even if the method is called from a different thread. This thread is forced to stop whatever it is doing and throw the Throwable object o. If this thread was suspended, it is resumed; if it was sleeping, it is awakened.

When an object is thrown out of the run() method associated with a Thread, the uncaughtException() method of the ThreadGroup for that Thread is called. If the thrown object is not an instance of the ThreadDeath class, uncaughtException() calls the thrown object’s printStackTrace() method and then the thread dies. The thread is never scheduled to run again.

If this Thread object’s stop() method is called before this thread is started, the ThreadDeath object is thrown as soon as the thread is started.
Parameter
o – The object to be thrown.

public final void suspend();

public final void suspend() method suspends a thread. The method causes this Thread object to temporarily be ineligible to be run. The thread becomes eligible to be run again after its resume() method is called. Calling this method for a thread that is already suspended has no effect.

public String toString();

public String toString() method returns a string representation of this Thread object.
This method returns a string representation of this Thread object.

Apart from these Thread class also has inherited methods from class- Object. They are as follows:

  • clone()
  • finalize()
  • hashCode()
  • notifyAll()
  • wait()
  • wait(long, int)
  • equals(Object)
  • getClass()
  • notify()
  • toString()
  • wait(long)

Read more on Inter thread communication here.

Where to use multiple threads or when to use a single thread?

If our program uses sequential logic, where one operation starts another operation and then must wait for another operation to complete before continuing one thread can implement the entire sequence. Using multi-thread in such cases results in more complex programs with no or slight benefits.

As there is a significant overhead to create and start a thread. If an operation involves only a few primitive statements, it is faster to handle with a single thread.

This is even true when the application is asynchronous. Threads share objects, so they need to use the synchronous mechanism to coordinate thread access and maintain state. The synchronization mechanism adds complexity to code.

Read more about thread creation here.

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

I am the founder and owner of the blog - TechTravelHub.com, always love to share knowledge on test automation,tools,techniques and tips.I am a passionate coder of Java and VBScript.I also publish articles on Travel ideas and great honeymoon destinations.Apart from these, I am a gear-head,love to drive across India. I have shared lots of articles here on How to travel several parts of India.Customization of cars aka car modification is my another hobby.Get in touch with me on [email protected]

Write A Comment