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.
public class Thread extends Object implements Runnable
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. |
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. |
static void sleep(long milliseconds) throws InterruptedException
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.
@FunctionalInterface
public interface Runnable
It provides only single method that must be implemented by the class.
Method | Description |
---|---|
run() | It runs the implemented thread. |
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:
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) {}
}
}
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.
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());
}
}
Example:
public class OutOfMemoryErrorDemo2
{
public static void main(String[] args)
{
Integer[] a = new Integer[100000*10000*1000];
System.out.println("Done");
}
}
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");
} }
}