DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

How does AI transform chaos engineering from an experiment into a critical capability? Learn how to effectively operationalize the chaos.

Data quality isn't just a technical issue: It impacts an organization's compliance, operational efficiency, and customer satisfaction.

Are you a front-end or full-stack developer frustrated by front-end distractions? Learn to move forward with tooling and clear boundaries.

Developer Experience: Demand to support engineering teams has risen, and there is a shift from traditional DevOps to workflow improvements.

Related

  • Memory Leak Due to Uncleared ThreadLocal Variables
  • Beyond Java Streams: Exploring Alternative Functional Programming Approaches in Java
  • Java Enterprise Matters: Why It All Comes Back to Jakarta EE
  • How to Identify the Underlying Causes of Connection Timeout Errors for MongoDB With Java

Trending

  • Operationalizing Data Quality in Cloud ETL Workflows: Automated Validation and Anomaly Detection
  • From Code to Customer: Building Fault-Tolerant Microservices With Observability in Mind
  • Cognitive Architecture: How LLMs Are Changing the Way We Build Software
  • Automating Kubernetes RBAC Sync With LDAP Entitlements Using Python
  1. DZone
  2. Coding
  3. Java
  4. Threads in Java

Threads in Java

A sequence or flow of execution in a Java program is called Thread. Threads are also known as lightweight process as they share the same data and process address space.

By 
Tarun Telang user avatar
Tarun Telang
DZone Core CORE ·
Jan. 22, 21 · Tutorial
Likes (19)
Comment
Save
Tweet
Share
8.9K Views

Join the DZone community and get the full member experience.

Join For Free

Overview of Threads

A sequence or flow of execution in a Java program is called a thread. 

Threads are also known as light weight processes, as they share the same data and process address space. 

Thread Priorities

Every thread has a priority based on which it gets preference for execution. Threads can have priorities ranging from [1…10]. 

Below is a list of some of the constants defined in the Thread class for specifying the thread priority: 

  • java.lang.Thread.MIN_PRIORITY = 1
  • java.lang.Thread.NORM_PRIORITY = 5
  • java.lang.Thread.MAX_PRIORITY = 10

Thread Scheduling

Threads are scheduled by Java runtime using fixed priority scheduling algorithm. 

Threads with higher priority generally (but this is not guaranteed) execute before threads with lower priority. 

However, JVM may decide to execute a lower priority thread before a higher priority thread to prevent starvation. A thread may, at any time, also decide to give up its right to execute by calling the Thread.yield() method. 

Threads can only yield the CPU to other threads having the same priority but if a thread attempts to yield to a lower priority thread the request is ignored.

Types of Threads

Threads are of two kinds namely a user thread and a daemon thread.

User Threads — User threads are normal threads and are generally used to run our program code.

Daemon Threads — daemon threads are also known as service provider threads. They are generally used to execute some system code. JVM terminates daemon threads if no user threads are running. Therefore daemon threads should not be used to perform our program logic.

Life Cycle of a Thread

  • NEW — A thread which is not yet started.
  • RUNNABLE — A thread which is executing in the JVM.
  • BLOCKED — A thread that is blocked for a monitor by another thread.
  • WAITING — A thread that is waiting for an unspecified amount of time for another thread(s) to finish an action.
  • TIMED_WAITING — A thread that is waiting for a specified amount of time for another thread to finish an action.
  • TERMINATED — An exited thread is in this state.

States of a thread graph

How to Use the Thread  Class in Java?

Below is an example of using the Thread class in Java.

Java
 




xxxxxxxxxx
1
28


 
1
// defining a thread 
2
class MyThread extends Thread {
3
  public void run() {
4
    // actions to be performed within thread      
5
    // . . .  
6
    System.out.println("Inside MyThread");
7
  }
8
}
9

          
10
class Main {
11
  public static void main(String[] args) {
12
    // creating a new thread and starting it 
13
    MyThread t = new MyThread();
14
    t.start();
15
    // changes the thread priority
16
    t.setPriority(Thread.MAX_PRIORITY);
17
    // t.setPriority(Thread.MIN_PRIORITY);
18

          
19
    try {
20
      // causes the thread to temprorarily stop execution
21
      t.sleep(1000); // 1000 milliseconds
22
    } catch (InterruptedException e) {
23
      e.getMessage();
24
    }
25

          
26
    System.out.println("Inside main method");
27
  }
28
}



How to Use the Runnable Interface in Java?

Below is an example using the Runnable interface.

Java
 




xxxxxxxxxx
1
32


 
1
// implementing a thread
2
class MyRunnable implements Runnable {
3
    public void run() {
4
        // actions to be performed within thread
5
        // ... 
6
        System.out.println("Inside MyThread");
7
    }
8
}
9

          
10
public class Main {
11
  public static void main(String[] args) {
12
    // creating and starting a new thread using runnable
13
    Runnable runnable = new MyRunnable();
14
    Thread t = new Thread(runnable);
15

          
16
    t.start();
17
    System.out.println("Inside main method");
18

          
19
    // changes the thread priority
20
    t.setPriority(Thread.MAX_PRIORITY);
21
    //t.setPriority(Thread.MIN_PRIORITY);
22

          
23
    try {
24
      // causes the thread to temprorarily stop execution
25
      t.sleep(1000); // 1000 milliseconds
26
    } catch (InterruptedException e) {
27
      e.getMessage();
28
    }
29
    
30
    System.out.println("Inside main method");
31
  }
32
}



How to Use Runnable Interface With Anonymous Class?

We can further simplify the above code snippet by using an anonymous class implementation of Runnable interface. 

Please see the code snippet below to understand this. 

Java
 




xxxxxxxxxx
1
49


 
1
public class Main {
2
  public static void main(String[] args) {
3
    // creating and starting a new thread using annonymous class
4
    Runnable runnable = new Runnable () {
5
      public void run() {
6
        // actions to be performed within thread
7
        // ... 
8
        System.out.println("Inside MyThread");
9
      }
10
    };
11

          
12
    Thread t = new Thread(runnable);
13
    t.start();
14
    System.out.println("Inside main method");
15
    // changes the thread priority
16
    t.setPriority(Thread.MAX_PRIORITY);
17
    //t.setPriority(Thread.MIN_PRIORITY);
18
    try {
19
      // causes the thread to temprorarily stop execution
20
      t.sleep(1000); // 1000 milliseconds
21
    } catch (InterruptedException e) {
22
      e.getMessage();
23
    }
24
  }
25
}



How to Use Runnable Implementation With Lambda Expression?

With Java 8 or later, Runnable implementation of thread can be further simplified by using lambda expressions for Runnable interface.

See the example below to understand how to implement this.

Java
 




xxxxxxxxxx
1
45


 
1
public class Main {
2
  public static void main(String[] args) {
3
    // creating and starting a new thread using annonymous class
4
    Runnable runnable = () -> {
5
      // actions to be performed within thread
6
      // ... 
7
      System.out.println("Inside MyThread");
8
    };
9

          
10
    Thread t = new Thread(runnable);
11
    t.start();
12
    System.out.println("Inside main method");
13
    // changes the thread priority
14
    t.setPriority(Thread.MAX_PRIORITY);
15
    //t.setPriority(Thread.MIN_PRIORITY);
16
    try {
17
      // causes the thread to temprorarily stop execution
18
      t.sleep(1000); // 1000 milliseconds
19
    } catch (InterruptedException e) {
20
      e.getMessage();
21
    }
22
  }
23
}



This is the most preferred approach due to the readability and conciseness of the code. 

Conclusion

The use of the Runnable interface is preferred as the first approach requiring extending the Thread class limits the MyThread class to further extend another class due to lack of Multiple Inheritance support in Java.

Java (programming language)

Published at DZone with permission of Tarun Telang. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Memory Leak Due to Uncleared ThreadLocal Variables
  • Beyond Java Streams: Exploring Alternative Functional Programming Approaches in Java
  • Java Enterprise Matters: Why It All Comes Back to Jakarta EE
  • How to Identify the Underlying Causes of Connection Timeout Errors for MongoDB With Java

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: