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.
Join the DZone community and get the full member experience.
Join For FreeOverview 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.
How to Use the Thread
Class in Java?
Below is an example of using the Thread
class in Java.
xxxxxxxxxx
// defining a thread
class MyThread extends Thread {
public void run() {
// actions to be performed within thread
// . . .
System.out.println("Inside MyThread");
}
}
class Main {
public static void main(String[] args) {
// creating a new thread and starting it
MyThread t = new MyThread();
t.start();
// changes the thread priority
t.setPriority(Thread.MAX_PRIORITY);
// t.setPriority(Thread.MIN_PRIORITY);
try {
// causes the thread to temprorarily stop execution
t.sleep(1000); // 1000 milliseconds
} catch (InterruptedException e) {
e.getMessage();
}
System.out.println("Inside main method");
}
}
How to Use the Runnable
Interface in Java?
Below is an example using the Runnable
interface.
xxxxxxxxxx
// implementing a thread
class MyRunnable implements Runnable {
public void run() {
// actions to be performed within thread
// ...
System.out.println("Inside MyThread");
}
}
public class Main {
public static void main(String[] args) {
// creating and starting a new thread using runnable
Runnable runnable = new MyRunnable();
Thread t = new Thread(runnable);
t.start();
System.out.println("Inside main method");
// changes the thread priority
t.setPriority(Thread.MAX_PRIORITY);
//t.setPriority(Thread.MIN_PRIORITY);
try {
// causes the thread to temprorarily stop execution
t.sleep(1000); // 1000 milliseconds
} catch (InterruptedException e) {
e.getMessage();
}
System.out.println("Inside main method");
}
}
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.
xxxxxxxxxx
public class Main {
public static void main(String[] args) {
// creating and starting a new thread using annonymous class
Runnable runnable = new Runnable () {
public void run() {
// actions to be performed within thread
// ...
System.out.println("Inside MyThread");
}
};
Thread t = new Thread(runnable);
t.start();
System.out.println("Inside main method");
// changes the thread priority
t.setPriority(Thread.MAX_PRIORITY);
//t.setPriority(Thread.MIN_PRIORITY);
try {
// causes the thread to temprorarily stop execution
t.sleep(1000); // 1000 milliseconds
} catch (InterruptedException e) {
e.getMessage();
}
}
}
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.
xxxxxxxxxx
public class Main {
public static void main(String[] args) {
// creating and starting a new thread using annonymous class
Runnable runnable = () -> {
// actions to be performed within thread
// ...
System.out.println("Inside MyThread");
};
Thread t = new Thread(runnable);
t.start();
System.out.println("Inside main method");
// changes the thread priority
t.setPriority(Thread.MAX_PRIORITY);
//t.setPriority(Thread.MIN_PRIORITY);
try {
// causes the thread to temprorarily stop execution
t.sleep(1000); // 1000 milliseconds
} catch (InterruptedException e) {
e.getMessage();
}
}
}
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.
Published at DZone with permission of Tarun Telang. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments