
- Groovy Tutorial
- Groovy - Home
- Groovy - Overview
- Groovy - Environment
- Groovy - Basic Syntax
- Groovy - Data Types
- Groovy - Variables
- Groovy - Optionals
- Groovy - Numbers
- Groovy - Strings
- Groovy - Ranges
- Groovy - Lists
- Groovy - Maps
- Groovy - Dates & Times
Groovy Operators
- Groovy - Operators
- Groovy - Arithmetic Operators
- Groovy - Assignment Operators
- Groovy - Relational Operators
- Groovy - Logical Operators
- Groovy - Bitwise Operators
- Groovy - Spaceship Operator
- Groovy - in Operator
- Groovy - Elvis Operator
- Groovy - Safe Navigation Operator
- Groovy Operator Precedence & Associativity
Control Statements
- Groovy - Decision Making
- Groovy - If Else Statement
- Groovy - Switch Statement
- Groovy - Loops
- Groovy - For Loop
- Groovy - For-in Loop
- Groovy - While Loop
- Groovy - Do While Loop
- Groovy - Break Statement
- Groovy - Continue Statement
Groovy File Handling
- Groovy - File I/O
- Java - Create a File
- Java - Write to File
- Java - Append to File
- Java - Read Files
- Java - Delete Files
- Java - File Properties
- Java - File Existence and Type
- Java - File Size
- Java - File Permissions
- Java - Directories
- Java - Listing Directories
- Java - Filtering Files/Directories
- Java - Deleting Directories
- Java - Renaming Files/Directories
Groovy Error & Exceptions
- Groovy - Exception Handling
- Groovy - try-catch Block
- Groovy - try-with-resources
- Groovy - Multi-catch Block
- Groovy - Nested try Block
- Groovy - Finally Block
- Groovy - throw Exception
- Groovy - Exception Propagation
- Groovy - Built-in Exceptions
- Groovy - Custom Exception
Groovy Multithreading
- groovy - Multithreading
- groovy - Thread Life Cycle
- groovy - Creating a Thread
- groovy - Starting a Thread
- groovy - Joining Threads
- groovy - Naming Thread
- groovy - Thread Scheduler
- groovy - Thread Pools
- groovy - Main Thread
- groovy - Thread Priority
- groovy - Daemon Threads
- groovy - Shutdown Hook
Groovy Synchronization
- groovy - Synchronization
- groovy - Block Synchronization
- groovy - Static Synchronization
- groovy - Inter-thread Communication
- groovy - Thread Deadlock
- groovy - Interrupting a Thread
- groovy - Thread Control
- groovy - Reentrant Monitor
- Groovy - Methods
- Groovy - Methods
- Groovy - Optional parenthesis
- Groovy - Named Arguments
- Groovy - Closures as Arguments
- Groovy - Method Overloading
- Groovy - Method Scope and Visibility
- Groovy - isCase Method
- Groovy - Implicit Return
- Groovy - Variable Arguments
- Groovy - Regular Expressions
- Groovy - Regular Expressions
- Groovy - Defining Regular Expressions
- Groovy - Matcher Object
- Groovy - Regex Tasks
- Groovy - XML
- Groovy - XML
- Groovy - Parsing XML
- Groovy - Creating XML
- Groovy - Modifying XML
- Groovy - Querying XML
- Groovy - Simplified Notation
- Groovy - Closure based Querying
- Groovy - Closure based Creation
- Groovy - JSON
- Groovy - JSON
- Groovy - Parsing JSON
- Groovy - Creating JSON using JsonOutput
- Groovy - Creating JSON using JsonBuilder
- Groovy - Modifying JSON
- Groovy - Error Handling
- Groovy - Handling JSON Arrays
- Groovy - JSON Array Operations
- Groovy - JSON Objects
- Groovy - JSON Object Operations
- Groovy - Generics
- Groovy - Generics
- Groovy - Declaring Generic Types
- Groovy - Bound Type Parameters
- Groovy - Wild Cards
- Groovy - Miscellaneous
- Groovy - Object Oriented
- Groovy - Closures
- Groovy - Annotations
- Groovy - JMX
- Groovy - DSLS
- Groovy - Database
- Groovy - Builders
- Groovy - Command Line
- Groovy - Unit Testing
- Groovy - Template Engines
- Groovy - Meta Object Programming
- Groovy Useful Resources
- Groovy - Quick Guide
- Groovy - Useful Resources
- Groovy - Discussion
Groovy - Multithreading
Groovy is a multi-threaded programming language which means we can develop multi-threaded program using Groovy. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs.
By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application.
Groovy Multithreading
Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program. To achieve the multithreading (or, write multithreaded code), you need java.lang.Thread class.
Life Cycle of a Thread in Groovy Multithreading
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread.

Following are the stages of the life cycle −
New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.
Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.
Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.
Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates.
Thread Priorities
Every Groovy thread has a priority that helps the operating system determine the order in which threads are scheduled.
Groovy thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent.
Create a Thread by Implementing a Runnable Interface
If your class is intended to be executed as a thread then you can achieve this by implementing a Runnable interface. You will need to follow three basic steps −
Step 1: Implement run() Method
As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of the run() method −
public void run( )
Step 2: Instantiate a Thread Object
As a second step, you will instantiate a Thread object using the following constructor −
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the name given to the new thread.
Step 3: Call Thread using start() Method
Once a Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method −
public void start();
Example - Create Thread by Implementing Runnable Interface
Here is an example that creates a new thread and starts running it −
Example.groovy
class Example { static void main(String[] args) { Runnable r1 = new RunnableDemo( "Thread-1"); r1.start(); Runnable r2 = new RunnableDemo( "Thread-2"); r2.start(); } } class RunnableDemo implements Runnable { private Thread t; private String threadName; RunnableDemo( String name) { threadName = name; println("Creating " + threadName ); } void run() { println("Running " + threadName ); try { for(int i = 4; i > 0; i--) { println("Thread: " + threadName + ", " + i); // Let the thread sleep for a while. Thread.sleep(50); } } catch (InterruptedException e) { println("Thread " + threadName + " interrupted."); } println("Thread " + threadName + " exiting."); } void start () { println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } }
Output
This will produce the following result−
Creating Thread-1 Starting Thread-1 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 4 Running Thread-2 Thread: Thread-2, 4 Thread: Thread-1, 3 Thread: Thread-2, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-1 exiting. Thread Thread-2 exiting.
Create a Thread by Extending a Thread Class
The second way to create a thread is to create a new class that extends Thread class using the following two simple steps. This approach provides more flexibility in handling multiple threads created using available methods in Thread class.
Step 1: Override run() Method
You will need to override run( ) method available in Thread class. This method provides an entry point for the thread and you will put your complete business logic inside this method. Following is a simple syntax of run() method −
public void run( )
Step 2: Call Thread using start() Method
Once Thread object is created, you can start it by calling start() method, which executes a call to run( ) method. Following is a simple syntax of start() method −
public void start( );
Example - Create Thread by Extending Thread Class
Here is the preceding program rewritten to extend the Thread −
Example.groovy
class Example { static void main(String[] args) { ThreadDemo t1 = new ThreadDemo( "Thread-1"); t1.start(); ThreadDemo t2 = new ThreadDemo( "Thread-2"); t2.start(); } } class ThreadDemo extends Thread { private Thread t; private String threadName; ThreadDemo( String name) { threadName = name; println("Creating " + threadName ); } void run() { println("Running " + threadName ); try { for(int i = 4; i > 0; i--) { println("Thread: " + threadName + ", " + i); // Let the thread sleep for a while. Thread.sleep(50); } } catch (InterruptedException e) { println("Thread " + threadName + " interrupted."); } println("Thread " + threadName + " exiting."); } void start () { println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } }
Output
This will produce the following result−
Creating Thread-1 Starting Thread-1 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 4 Running Thread-2 Thread: Thread-2, 4 Thread: Thread-1, 3 Thread: Thread-2, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-1 exiting. Thread Thread-2 exiting.
Thread Methods
Following is the list of important methods available in the Thread class.
Sr.No. | Method & Description |
---|---|
1 |
public void start() Starts the thread in a separate path of execution, then invokes the run() method on this Thread object. |
2 |
public void run() If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object. |
3 |
public final void setName(String name) Changes the name of the Thread object. There is also a getName() method for retrieving the name. |
4 |
public final void setPriority(int priority) Sets the priority of this Thread object. The possible values are between 1 and 10. |
5 |
public final void setDaemon(boolean on) A parameter of true denotes this Thread as a daemon thread. |
6 |
public final void join(long millisec) The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes. |
7 |
public void interrupt() Interrupts this thread, causing it to continue execution if it was blocked for any reason. |
8 |
public final boolean isAlive() Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion. |
The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread.
Sr.No. | Method & Description |
---|---|
1 |
public static void yield() Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled. |
2 |
public static void sleep(long millisec) Causes the currently running thread to block for at least the specified number of milliseconds. |
3 |
public static boolean holdsLock(Object x) Returns true if the current thread holds the lock on the given Object. |
4 |
public static Thread currentThread() Returns a reference to the currently running thread, which is the thread that invokes this method. |
5 |
public static void dumpStack() Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application. |
Example - Using Thread methods
The following Example program demonstrates some of these methods of the Thread class. Consider a class DisplayMessage which implements Runnable −
// Create a thread to implement Runnable class DisplayMessage implements Runnable { private String message; DisplayMessage(String message) { this.message = message; } void run() { while(true) { println(message); } } }
Following is another class which extends the Thread class −
// Create a thread to extentd Thread class GuessANumber extends Thread { private int number; GuessANumber(int number) { this.number = number; } void run() { int counter = 0; int guess = (int) (Math.random() * 100 + 1); while(guess != number) { guess = (int) (Math.random() * 100 + 1); println(this.getName() + " guesses " + guess); counter++; } println("** Correct!" + this.getName() + "in" + counter + "guesses.**"); } }
Following is the main program, which makes use of the above-defined classes −
class Example { static void main(String [] args) { Runnable hello = new DisplayMessage("Hello"); Thread thread1 = new Thread(hello); thread1.setDaemon(true); thread1.setName("hello"); println("Starting hello thread..."); thread1.start(); Runnable bye = new DisplayMessage("Goodbye"); Thread thread2 = new Thread(bye); thread2.setPriority(Thread.MIN_PRIORITY); thread2.setDaemon(true); println("Starting goodbye thread..."); thread2.start(); println("Starting thread3..."); Thread thread3 = new GuessANumber(27); thread3.start(); try { thread3.join(); } catch (InterruptedException e) { println("Thread interrupted."); } println("Starting thread4..."); Thread thread4 = new GuessANumber(75); thread4.start(); println("main() is ending..."); } } class DisplayMessage implements Runnable { private String message; DisplayMessage(String message) { this.message = message; } void run() { while(true) { println(message); } } } class GuessANumber extends Thread { private int number; GuessANumber(int number) { this.number = number; } void run() { int counter = 0; int guess = (int) (Math.random() * 100 + 1); while (guess != number){ guess = (int) (Math.random() * 100 + 1); println(this.getName() + " guesses " + guess); counter++; } println("** Correct!" + this.getName() + "in" + counter + "guesses.**"); } }
Output
This will produce the following result−
Starting hello thread... Starting goodbye thread... Hello Hello Hello Hello Hello Hello Goodbye Goodbye Goodbye Goodbye Goodbye .......
Major Groovy Multithreading Concepts
While doing Multithreading programming in Groovy, you would need to have the following concepts very handy −