Java Thread Class
Thread class is the main class on which Java's Multithreading system is based. Thread class, along with its companion interface Runnable will be used to create and run threads for utilizing Multithreading feature of Java.
It provides constructors and methods to support multithreading. It extends object class and implements Runnable interface.
Signature of Thread class
public class Thread extends Object implements Runnable
Thread Class Priority Constants
Field |
Description |
MAX_PRIORITY |
It represents the maximum priority that a thread can have. |
MIN_PRIORITY |
It represents the minimum priority that a thread can have. |
NORM_PRIORITY |
It represents the default priority that a thread can have. |
Constructors of Thread class
- Thread()
- Thread(String str)
- Thread(Runnable r)
- Thread(Runnable r, String str)
- Thread(ThreadGroup group, Runnable target)
- Thread(ThreadGroup group, Runnable target, String name)
- Thread(ThreadGroup group, Runnable target, String name, long stackSize)
- Thread(ThreadGroup group, String name)
Thread Class Methods
Thread class also defines many methods for managing threads. Some of them are,
Method | Description |
setName() | to give thread a name |
getName() | return thread's name |
getPriority() | return thread's priority |
isAlive() | checks if thread is still running or not |
join() | Wait for a thread to end |
run() | Entry point for a thread |
sleep() | suspend thread for a specified time |
start() | start a thread by calling run() method |
activeCount() | Returns an estimate of the number of active threads in the current thread's thread group and its subgroups. |
checkAccess() | Determines if the currently running thread has permission to modify this thread. |
currentThread() | Returns a reference to the currently executing thread object. |
dumpStack() | Prints a stack trace of the current thread to the standard error stream. |
getId() | Returns the identifier of this Thread. |
getState() | Returns the state of this thread. |
getThreadGroup() | Returns the thread group to which this thread belongs. |
interrupt() | Interrupts this thread. |
interrupted() | Tests whether the current thread has been interrupted. |
isAlive() | Tests if this thread is alive. |
isDaemon() | Tests if this thread is a daemon thread. |
isInterrupted() | Tests whether this thread has been interrupted. |
setDaemon(boolean on) | Marks this thread as either a daemon thread or a user thread. |
setPriority(int newPriority) | Changes the priority of this thread. |
yield() | A hint to the scheduler that the current thread is willing to yield its current use of a processor. |
Some Important points to Remember
- When we extend Thread class, we cannot override setName() and getName() functions, because they are declared final in Thread class.
- While using sleep(), always handle the exception it throws.
static void sleep(long milliseconds) throws InterruptedException
Runnable Interface
It also used to create thread and should be used if you are only planning to override the run()
method and no other Thread methods.
Signature
@FunctionalInterface
public interface Runnable
Runnable Interface Method
It provides only single method that must be implemented by the class.
Method | Description |
run() | It runs the implemented thread. |
Shutdown hook
In Java, Shutdown hook is used to clean-up all the resource, it means closing all the files, sending alerts etc. We can also save the state when the JVM shuts down. Shutdown hook mostly used when any code is to be executed before any JVM shuts down. Following are some of the reasons when the JVM shut down:
- Pressing ctrl+c on the command prompt
- When the System.exit(int) method is invoked.
- When user logoff or shutdown etc
addShutdownHook(Thread hook)
The addShutdownHook(Thread hook) method is used to register the thread with the virtual machine. This method is of Runtime class.
Example:
class Demo6 extends Thread
{
public void run()
{
System.out.println("Shutdown hook task is Now completed...");
}
}
public class ShutdownDemo1
{
public static void main(String[] args)throws Exception
{
Runtime obj=Runtime.getRuntime();
obj.addShutdownHook(new Demo6());
System.out.println("Now main method is sleeping... For Exit press ctrl+c");
try
{
Thread.sleep(4000);
}
catch (Exception e) {}
}
}
OutOfMemory Exception
In Java, as we know that all objects are stored in the heap. The objects are created using the new keyword. The OutOfMemoryError occurs as follow:
This error occurs when Java Virtual Machine is not able to allocate the object because it is out of memory and no memory can be available by the garbage collector.
The meaning of OutOfMemoryError is that something wrong is in the program. Many times the problem can be out of control when the third party library caches strings.
Basic program in which OutOfMemoryError can occur
Example:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class OutOfMemoryDemo1 {
public static void main(String[] args) {
Listobj = new ArrayList<>();
Random obj1= new Random();
while (true)
obj.add(obj1.nextInt());
}
}
Program in which OutOfMemoryError can occur because of low memory
Example:
public class OutOfMemoryErrorDemo2
{
public static void main(String[] args)
{
Integer[] a = new Integer[100000*10000*1000];
System.out.println("Done");
}
}
Program in which OutOfMemoryError can occur, when Garbage Collector exceed the limit
Example:
import java.util.*;
public class OutOfMemoryErrorDemo2{
public static void main(String args[]) throws Exception
{
Map a = new HashMap();
a = System.getProperties();
Random b = new Random();
while (true) {
a.put(b.nextInt(), "randomValue");
} }
}