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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong

Trending

  • Spring AI on Local LLMs
  • Why Kotlin or Java Is the Wrong Question For Enterprises
  • Batching Strategies: Throughput vs Latency in Practice
  • To Switch, or Not to Switch the AI Model

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Jan. 22, 21 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
9.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Searching Kafka Without an Index: Lessons From Building Message Search for Kafdrop
  • ScyllaDB in Enterprise Java: High-Performance NoSQL With Eclipse JNoSQL
  • Member Spotlight: Shai Almong

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook