AppDividend
Latest Code Tutorials

Java Thread Class Tutorial With Example | Java.lang.Thread Class

0

Java Thread Class Tutorial With Example | Java.lang.Thread Class is today’s topic. The java.lang.Thread class is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently. The Thread class, along with its methods and the Runnable interface, builds the multithreading system in Java. Multithreading or Multithreaded programming is a concept in Java, and Computer Science in general, in which multiple threads can be executed simultaneously.

Java Thread Class

Following are the essential points about Thread in Java.

  1. Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority.

  2. Each thread may or may not also be marked as a daemon.

  3. There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread.
  4. Another way to create a thread is to declare a class that implements the Runnable interface.

#Class Declaration

Following is the declaration for java.lang.Thread class.

public class Thread
   extends Object
      implements Runnable

The following command in the terminal will show you the full definition of the Thread class in Java.

javap java.lang.Thread
/*
Note: Following is the in-built Thread class defined in java.lang
package. This class is shown here just for reference.

This piece of code will not compile by itself.
*/


/*
The Thread class can be seen in the terminal by using the following
command.
~$ javap java.lang.Thread

*/

/*
Compiled from "Thread.java"
*/

public class java.lang.Thread implements java.lang.Runnable {

  java.lang.ThreadLocal$ThreadLocalMap threadLocals;
  java.lang.ThreadLocal$ThreadLocalMap inheritableThreadLocals;
  volatile java.lang.Object parkBlocker;
  public static final int MIN_PRIORITY;
  public static final int NORM_PRIORITY;
  public static final int MAX_PRIORITY;
  long threadLocalRandomSeed;
  int threadLocalRandomProbe;
  int threadLocalRandomSecondarySeed;
  void blockedOn(sun.nio.ch.Interruptible);
  public static native java.lang.Thread currentThread();
  public static native void yield();
  public static native void sleep(long) throws java.lang.InterruptedException;
  public static void sleep(long, int) throws java.lang.InterruptedException;
  protected java.lang.Object clone() throws java.lang.CloneNotSupportedException;
  public java.lang.Thread();
  public java.lang.Thread(java.lang.Runnable);
  java.lang.Thread(java.lang.Runnable, java.security.AccessControlContext);
  public java.lang.Thread(java.lang.ThreadGroup, java.lang.Runnable);
  public java.lang.Thread(java.lang.String);
  public java.lang.Thread(java.lang.ThreadGroup, java.lang.String);
  public java.lang.Thread(java.lang.Runnable, java.lang.String);
  public java.lang.Thread(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String);
  public java.lang.Thread(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long);
  public synchronized void start();
  public void run();
  public final void stop();
  public final synchronized void stop(java.lang.Throwable);
  public void interrupt();
  public static boolean interrupted();
  public boolean isInterrupted();
  public void destroy();
  public final native boolean isAlive();
  public final void suspend();
  public final void resume();
  public final void setPriority(int);
  public final int getPriority();
  public final synchronized void setName(java.lang.String);
  public final java.lang.String getName();
  public final java.lang.ThreadGroup getThreadGroup();
  public static int activeCount();
  public static int enumerate(java.lang.Thread[]);
  public native int countStackFrames();
  public final synchronized void join(long) throws java.lang.InterruptedException;
  public final synchronized void join(long, int) throws java.lang.InterruptedException;
  public final void join() throws java.lang.InterruptedException;
  public static void dumpStack();
  public final void setDaemon(boolean);
  public final boolean isDaemon();
  public final void checkAccess();
  public java.lang.String toString();
  public java.lang.ClassLoader getContextClassLoader();
  public void setContextClassLoader(java.lang.ClassLoader);
  public static native boolean holdsLock(java.lang.Object);
  public java.lang.StackTraceElement[] getStackTrace();
  public static java.util.Map<java.lang.Thread, java.lang.StackTraceElement[]> getAllStackTraces();
  public long getId();
  public java.lang.Thread$State getState();
  public static void setDefaultUncaughtExceptionHandler(java.lang.Thread$UncaughtExceptionHandler);
  public static java.lang.Thread$UncaughtExceptionHandler getDefaultUncaughtExceptionHandler();
  public java.lang.Thread$UncaughtExceptionHandler getUncaughtExceptionHandler();
  public void setUncaughtExceptionHandler(java.lang.Thread$UncaughtExceptionHandler);
  static void processQueue(java.lang.ref.ReferenceQueue<java.lang.Class<?>>, java.util.concurrent.ConcurrentMap<? extends java.lang.ref.WeakReference<java.lang.Class<?>>, ?>);
  static {};

}

The following flow chart shows that the Thread class extends Object and implements the Runnable interface.

 

Java Thread Class

#Constructors of Thread Class

#Thread()

Instantiates Thread.

#Thread(Runnable obj)

Instantiates Thread passing an object reference of Runnable as a parameter, having obj as its run object.

#Thread(String str)

Instantiates Thread passing a String object str as a parameter, having str as the name of the thread.

#Thread(Runnable obj, String str)

Instantiates Thread passing an object reference of Runnable and a String object str as parameters, having obj as its run object and str as the name of the thread.

#Thread(ThreadGroup grp, Runnable obj)

Instantiates Thread passing an object reference of Runnable and an object reference of ThreadGroup as parameters, having obj as its run object and grp as the thread group to which this thread will belong to.

#Thread(ThreadGroup grp, String str)

Instantiates Thread passing an object reference of ThreadGroup and a String object reference as parameters, having grp as the thread group to which this thread will belong to, and str as the name of the thread.

#Thread(ThreadGroup grp, Runnable obj, String str

Instantiates Thread passing an object reference of Runnable and an object reference of ThreadGroup as well as a String object reference as parameters, having obj as its run object, grp as the thread group to which this thread will belong to, and str as the name of the thread.

#Thread(ThreadGroup grp, Runnable obj, String str, long size)

Instantiates Thread passing an object reference of Runnable and an object reference of ThreadGroup, a String object reference, and a long reference  as parameters, having obj as its run object , grp as the thread group to which this thread will belong to, str as the name of the thread and size as the specified stack size.

#Methods of Thread Class in Java

The following are some of the important methods of the Thread class in Java.

#run()

Subclasses of Thread override this method to form the actual body of the thread. See the syntax.

public void run()

#toString()

Returns a string representation of the invoking thread which includes the name, priority and the group of the thread. See the syntax.

public String toString()

#start()

Begins the execution of the invoking thread. See the following syntax.

public void start()

#join()

Waits for the invoking thread to die. See the syntax.

public final void join() throws InterruptedException

#join(long milliseconds)

Waits almost milliseconds for the invoking thread to die. See the syntax.

public final void join(long millisecs) throws InterruptedException ]

#sleep(long millisecs)

Makes the invoking thread temporarily cease execution for millisecs milliseconds. See the syntax.

public static void sleep(long millisecs) throws InterruptedException

#setName(String str)

Names the thread as the argument passed. See the syntax.

public final void setName(String str)

#setPriority(int prior)

Changes the priority of the invoking thread. See the syntax.

public final void setPriotity(int prior)

#setDaemon(boolean b)

Marks the invoking thread as either a user thread or daemon thread. See the syntax.

public final void setDaemon(boolean b)

#yield()

Gives a hint to the scheduler that the invoking thread is willing to yield the CPU. See the syntax.

public static void yield()

#activeCount()

Returns the number of active threads in the invoking thread’s group and subgroups. See the syntax.

public static int activeCount()

#getStackTrace()

Returns an array of stack trace elements which represents the stack dump of the invoking thread. See the following syntax.

public StackTraceElement[] getStackTrace()

#getState()

Returns the state of the invoking thread. See the syntax.

public Thread.State getState()

#currentThread()

Returns a reference to the current thread object. See the syntax.

public static Thread currentThread()

#getContextClassLoader()

Returns the context ClassLoader for the invoking thread. See the syntax.

public ClassLoader getContextClassLoader()

#getId()

Returns the id of the invoking thread. See the syntax.

public long getId()

#getThreadGroup()

Returns the thread group to which the invoking thread belongs. See the syntax.

public final ThreadGroup getThreadGroup()

#interrupt()

Interrupts the invoking thread. See the syntax.

public void interrupt()

#isAlive()

Checks if the invoking thread is alive. If so, returns true. Otherwise, returns false. See the syntax.

public final boolean isAlive()

#checkAccess()

Determines if the currently running thread has permission to modify the thread which invokes it. See the syntax.

public final void checkAccess()

#isDaemon()

Determines whether the invoking thread is a daemon thread or a user thread. The syntax is following.

public final boolean isDaemon()

#isInterrupted()

Determines whether the invoking thread has been interrupted. The syntax is following.

public boolean isInterrupted()

#setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler e)

If the thread terminates abruptly due to an uncaught exception, handler e is set. See the syntax.

public void setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler e)

#setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler e)

If the thread terminates abruptly due to an uncaught exception, handler e is set as default handler when no other handler handles the exception. See the syntax.

public static void setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler e)

#setContextClassLoader(ClassLoader c) 

Sets the context ClassLoader for the thread which invokes it. See the syntax.

public void setContextClassLoader(ClassLoader c)

#clone()

Throws CloneNotSupportedException. See the syntax.

protected Object clone() throws CloneNotSupportedException

#dumpStack()

A stack trace of the invoking thread is printed to the standard error stream. See the syntax.

public static void dumpStack()

#enumerate(Thread[] t)

All the active threads in the invoking thread’s thread group and subgroups are copied into the specified array t. See the syntax.

public static int enumerate(Thread[] t)

#getAllStackTraces()

For all live threads, this method returns a map of stack traces. See the syntax.

public static Map getAllStackTraces()

#getDefaultUncaughtExceptionHandler()

If the thread terminates abruptly due to an uncaught exception, the default handler handles it when no other handler handles the exception. Returns the said default handler. See the syntax.

public static Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()

#getName()

Returns the name of the thread. See the syntax.

public final String getName()

#getPriority() 

Returns the priority of the thread. See the syntax.

public final int getPriority()

#getUncaughtExceptionHandler()

If the thread terminates abruptly due to an uncaught exception, the handler which will be invoked is returned by this method. See the syntax.

public Thread.UncaughtExceptionHandler getUncaughtExceptionHandler()

#holdsLock(Object ob)

Checks whether the current thread holds the monitor lock on ob. See the syntax.

public static boolean holdsLock(Object ob)

#interrupted()

Determines whether the current thread has been interrupted. See the following syntax.

public static boolean interrupted()

The following program demonstrates the use of some of the methods stated above.

class SecondThread extends Thread {
	SecondThread() {
			super("Second Thread");
			start(); 
	}
	public void run() {
			try {
				for(int i = 5; i > 0; i--) {
				Thread.sleep(1);
				}
			} catch (InterruptedException e) {
			System.out.println("Second interrupted.");
			}
			
	}
}

class NewEx0 {
	public static void main(String args[]) {
		SecondThread obj = new SecondThread();

		ClassLoader c = obj.getContextClassLoader();
		System.out.println("Context ClassLoader: " + c);

		System.out.println("Active Count: " + obj.activeCount());
		obj.checkAccess();

		System.out.println();

		System.out.println("Name: " + obj.getName());
		System.out.println("ID: " + obj.getId());
		System.out.println("Priotity: " + obj.getPriority());
		System.out.println("State: " + obj.getState());

		obj.interrupt();
		
		try{
			Thread.sleep(1);
		}catch(InterruptedException e){
			System.out.println("InterruptedException");
		}
		
		System.out.println("Interrupted: " + obj.interrupted());
		System.out.println("Alive: " + obj.isAlive());

		obj.setDaemon(true);

		System.out.println("Daemon: " + obj.isDaemon());


		try {
		for(int i = 5; i > 0; i--) {
			Thread.sleep(2);
		}
		} catch (InterruptedException e) {
		System.out.println("Main thread interrupted.");
		}
		
	}
}

See the following output.

 

Java Thread Class Tutorial

#Thread Class Example

The following program demonstrates the use of the Thread class.

class SecondThread extends Thread {
	SecondThread() {
		super("Second Thread");
		System.out.println("Second thread: " + this);
		start(); 
	}
	public void run() {
		try {
			for(int i = 5; i > 0; i--) {
			        System.out.println("Second Thread: " + i);
				Thread.sleep(1000);
		        }
		} catch (InterruptedException e) {
			System.out.println("Second interrupted.");
		}
		        System.out.println("Exiting second thread.");
		}
	}

class ThreadClassDemo {
	public static void main(String args[]) {
		new SecondThread(); 
		try {
		      for(int i = 5; i > 0; i--) {
		          System.out.println("Main Thread: " + i);
		          Thread.sleep(2000);
		       }
		} catch (InterruptedException e) {
		     System.out.println("Main thread interrupted.");
		}
		 System.out.println("Exiting Main thread.");
             }
	}

See the following output.

 

Java.lang.Thread Class

Finally, Java Thread Class Tutorial With Example | Java.lang.Thread Class is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.