Here we will see Thread class constructors and methods with example.
Thread class constructors:-
Thread()
Thread(Runnable target)
Thread(Runnable target, String name)
Thread(String name)
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() – Default constructor Used to create a new Thread object.
package multithreading; import java.util.Set; import java.util.concurrent.Callable; public class ThreadExample extends Thread { public static void main(String[] args) { Thread t1 = new Thread(); t1.start(); System.out.println("Thread has been created with name :- " + t1.getName()); } }
Output is – Thread has been created with name :- Thread-0
Thread(Runnable target) – We can pass Runnable reference and create a new Thread object.
package multithreading; class Book implements Runnable { @Override public void run() { System.out.println("perform some task"); } } public class ThreadExample extends Thread { public static void main(String[] args) { Thread t1 = new Thread(new Book()); t1.start(); System.out.println("Thread has been created with name :- " + t1.getName()); } }
Output is –
Thread has been created with name :- Thread-0
perform some task
Note – Sequence of output may change. In line 16 we are passing Book object. Since Book class is implementing the Runnable interface, we can pass as a parameter for creating a new Thread object.
Thread(Runnable target, String name) – We can create a new Thread object using this constructor, passing Runnable reference as first parameter and also we can provide some name for newly created thread. Did you notice in the above example by default we have some i.e Thread -0. We can specify some different name.
package multithreading; class Book implements Runnable { @Override public void run() { System.out.println("perform some task"); } } public class ThreadExample extends Thread { public static void main(String[] args) { Thread t1 = new Thread(new Book(), "book thread"); t1.start(); System.out.println("Thread has been created with name :- " + t1.getName()); } }
Output is –
Thread has been created with name :- book thread
perform some task
In the above program line 16, we have given the thread name “book thread” and yes thread is created with the same name.
Thread(String name) – We can create a new Thread object and specify some name.
package multithreading; public class ThreadExample extends Thread { public static void main(String[] args) { Thread t1 = new Thread("some name"); t1.start(); System.out.println("Thread has been created with name :- " + t1.getName()); } }
Output is – Thread has been created with name :- some name
Thread(ThreadGroup group, Runnable target) – We can create a new Thread passing ThreadGroup class and Runnable interface as a parameter.
package multithreading; class Book implements Runnable { @Override public void run() { // some logic } } public class ThreadExample extends Thread { public static void main(String[] args) { Thread t1 = new Thread(new ThreadGroup("Thread Group 1"), new Book()); t1.start(); System.out.println("Thread created with name :- " + t1.getName()); } }
Output is – Thread created with name :- Thread-0
Thread(ThreadGroup group, Runnable target, String name) –
package multithreading; class Book implements Runnable { @Override public void run() { // some logic } } public class ThreadExample extends Thread { public static void main(String[] args) { Thread t1 = new Thread(new ThreadGroup("Thread Group 1"), new Book(),"book thread"); t1.start(); System.out.println("Thread created with name :- " + t1.getName()); } }
Output is – Thread created with name :- book thread
Thread(ThreadGroup group, Runnable target, String name, long stackSize) –
package multithreading; class Book implements Runnable { @Override public void run() { // some logic } } public class ThreadExample extends Thread { public static void main(String[] args) { Thread t1 = new Thread(new ThreadGroup("Thread Group 1"), new Book(),"book thread",10); t1.start(); System.out.println("Thread created with name :- " + t1.getName()); } }
Output is – Thread created with name :- book thread
Thread(ThreadGroup group, String name) –
package multithreading; public class ThreadExample extends Thread { public static void main(String[] args) { Thread t1 = new Thread(new ThreadGroup("Thread Group 1"), "thread name1"); t1.start(); System.out.println("Thread group name is :- " + t1.getThreadGroup().getName()); System.out.println("Thread group name is :- " + t1.getName()); } }
Output is –
Thread group name is :- Thread Group 1
Thread group name is :- thread name1
Note – Output may vary. You may get NullPointerException.
Exception in thread “main” java.lang.NullPointerException
at multithreading.ThreadExample.main(ThreadExample.java:8)
Methods of Thread class –
- public static int activeCount() – Returns the number of active threads in the current thread’s thread group and its subgroups.
- public final void checkAccess() – Determines if the currently running thread has permission to modify this thread.
- public static native Thread currentThread() – Returns a reference to the currently executing thread object.
- public static void dumpStack() – Prints a stack trace of the current thread to the standard error stream.
- public static int enumerate(Thread tarray[]) – Copies into the specified array every active thread in the current thread’s thread group and its subgroups.
- public static Map<Thread, StackTraceElement[]> getAllStackTraces() – Returns a map of stack traces for all live threads.
- public ClassLoader getContextClassLoader() – Returns a ClassLoader for this Thread.
- public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() – Returns the default exception handler, when a thread abruptly terminates due to an uncaught exception.
- public long getId() – Returns the id as a number of this Thread.
- public final String getName() – Returns the name of a thread.
- public final int getPriority() – Returns the priority of thread.
- public StackTraceElement[] getStackTrace() – Returns an array of stack trace elements representing the stack dump of this thread.
- public State getState() – Returns the state of the thread.
- public final ThreadGroup getThreadGroup() – Returns the thread group to which this thread belongs.
- public UncaughtExceptionHandler getUncaughtExceptionHandler() – Returns the handler invoked when this thread abruptly terminates due to an uncaught exception.
- public static native boolean holdsLock(Object obj) – Returns true if and only if the current thread holds the monitor lock on the specified object.
- public void interrupt() – Used to Interrupt the thread.
- public static boolean interrupted() – Checks whether the current thread has been interrupted or not.
- public final native boolean isAlive() – Checks thread is live or not.
- public final boolean isDaemon() – Checks thread is daemon or not.
- public boolean isInterrupted() – Checks whether this thread has been interrupted.
- public final void join() throws InterruptedException – Waits for this thread to die.
- public final synchronized void join(long millis) throws InterruptedException- Waits at most millis milliseconds for this thread to die.
- public final synchronized void join(long millis, int nanos) throws InterruptedException – Waits at most millis milliseconds plus nanos nanoseconds for this thread to die.
- public void run() – If this thread was constructed using a separate
Runnable
run object, then thatRunnable
object’srun
method is called; otherwise, this method does nothing and returns. - public void setContextClassLoader(ClassLoader cl) – Sets the context ClassLoader for this Thread.
- public final void setDaemon(boolean on) – Marks this thread as either a daemon thread or a user thread.
- public final synchronized void setName(String name) – Changes the name of this thread to be equal to the argument name.
- public final void setPriority(int newPriority) – Used to Change the priority of this thread.
- public static native void sleep(long millis) throws InterruptedException – Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
- public static void sleep(long millis, int nanos) throws InterruptedException – Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers.
- public synchronized void start() – Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
- public final void stop() – Used to stop a thread.
- public static native void yield() – A hint to the scheduler that the current thread is willing to yield its current use of a processor.