Last Updated: 11 July, 2023
In this tutorial, we are going to discuss all about creating threads in Java. We'll go over what a thread is and how many different ways we can create them in Java.
In Java, a thread is a lightweight sub-process; it is a small part of a process that can run independently and contains a separate path of execution. Threads consume fewer resources while creating and existing.
Java programs are executed by the main thread. When a Java program is executed, the main thread is automatically created, and all other threads are invoked by the main thread.
There are two ways to create a thread in Java:
Runnable is an interface in the java.lang package. It has only one method, which is called the run() method. Any Java class that needs a thread to execute its instance should implement the Runnable interface.
Runnable Interface Declaration
public interface Runnable
👉 We need to follow the given steps for creating a thread by implementing the Runnable Interface in Java.
Step 1: Create a class that implements the Runnable interface.
Step 2: Override the run() method with the code that is to be executed by the thread.
Step 3: Inside the main() method, create an object of the class.
Step 4: Pass the created object as a parameter to the constructor of the Thread class.
Step 5: Call the start() method.
Let's implement these steps and create a thread in Java as given below in the example.
Example 1 : Creating a thread by implementing the Runnable Interface.
Output
Inside Runnable - run() method...
Thread is a Java class in the java.lang package. It extends the Object class and implements the Runnable interface. Thread classes provide constructors and methods to create and perform operations on threads.
👉 We need to follow the given steps for creating a thread by extending the Thread class in Java.
Step 1: Create a class that extends the Thread class.
Step 2: Override the run() method with the code that is to be executed by the thread.
Step 3: Inside the main() method, create the object of the class.
Step 4: Call the start() method.
Let's implement these steps and create a thread in Java as given below in the example.
Example 2 : Creating a thread by extending the Thread class
Output
Thread is running...
Thread is a Java class in the java.lang package. It extends the Object class and implements the Runnable interface. The Thread class provides the following constructors and methods to create and perform operations on a thread.
Thread Class Declaration
public class Thread extends Object implements Runnable
Thread Class Constructors
Constructors | Description |
---|---|
Thread() | Allocates a new Thread object. |
Thread(Runnable target) | Allocates a new Thread object. |
Thread(Runnable target, String name) | Allocates a new Thread object. |
Thread(String name) | Allocates a new Thread object. |
Thread(ThreadGroup group, Runnable target) | Allocates a new Thread object. |
Thread(ThreadGroup group, Runnable target, String name) | Allocates a new Thread object so that it has targeted as its run object, has the specified name as its name, and belongs to the thread group referred to by a group. |
Thread(ThreadGroup group, Runnable target, String name, long stackSize) | Allocates a new Thread object so that it has targeted as its run object, has the specified name as its name, and belongs to the thread group referred to by group, and has the specified stack size. |
Thread(ThreadGroup group, String name) | Allocates a new Thread object. |
Thread Class Methods
Methods | Description |
---|---|
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 |
clone() | Throws CloneNotSupportedException as a Thread can not be meaningfully cloned |
currentThread() | Returns a reference to the currently executing thread object |
dumpStack() | Prints a stack trace of the current thread to the standard error stream |
enumerate(Thread[] tarray) | Copies into the specified array every active thread in the current thread’s thread group and its subgroups |
getAllStackTraces() | Returns a map of stack traces for all live threads |
getContextClassLoader() | Returns the context ClassLoader for this Thread |
getDefaultUncaughtExceptionHandler() | Returns the default handler invoked when a thread abruptly terminates due to an uncaught exception |
getId() | Returns the identifier of this Thread |
getName() | Returns this thread’s name |
getPriority() | Returns this thread’s priority |
getStackTrace() | Returns an array of stack trace elements representing the stack dump of this thread |
getState() | Returns the state of this thread |
getThreadGroup() | Returns the thread group to which this thread belongs |
getUncaughtExceptionHandler() | Returns the handler invoked when this thread abruptly terminates due to an uncaught exception |
holdsLock(Object obj) | Returns true if and only if the current thread holds the monitor lock on the specified object |
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 |
join() | Waits for this thread to die |
join(long millis) | Waits at most millis milliseconds for this thread to die |
run() | If this thread was constructed using a separate Runnable run object, then that Runnable object’s run method is called; otherwise, this method does nothing and returns |
setContextClassLoader(ClassLoader cl) | Sets the context ClassLoader for this Thread |
setDaemon(boolean on) | Marks this thread as either a daemon thread or a user thread |
setDefaultUncaughtExceptionHandler (Thread.UncaughtExceptionHandler eh) | Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread |
setName(String name) | Changes the name of this thread to be equal to the argument name. |
setUncaughtExceptionHandler (Thread.UncaughtExceptionHandler eh) | Set the handler invoked when this thread abruptly terminates due to an uncaught exception |
setPriority(int newPriority) | Changes the priority of this thread |
sleep(long millis) | 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 |
start() | Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread |
toString() | Returns a string representation of this thread, including the thread’s name, priority, and thread group |
yield() | A hint to the scheduler that the current thread is willing to yield its current use of a processor |
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com
We can start a thread twice in Java?
Ans. No, it is not possible to start a thread twice in Java. Attempting to do so will result in an IllegalThreadStateException.
public static void main(String args[])
{
MyThread mt = new MyThread();
mt.start();
mt.start(); // Exception thrown - IllegalThreadStateException
}
What if we called the run() method directly instead of the start() method?
Ans. If the run() method is called directly instead of the start() method, the run() method will be treated as a normal overridden method of the thread class (or runnable interface). This run method will be executed within the context of the current thread, not in a new thread.