Class Thread in Java

0
201
Spread the love
  • 24
  • 23
  • 14
  • 12
  •  
  •  
  •  
  • 12
  •  
  •  
    85
    Shares

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.

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.

Spread the love
  • 24
  • 23
  • 14
  • 12
  •  
  •  
  •  
  • 12
  •  
  •  
    85
    Shares

LEAVE A REPLY

Please enter your comment!
Please enter your name here