#
Threads in Java (with example)
This tutorial will explain to you how to use threads in Java and will present you an example.
Multithreading
refers to two or more tasks executing concurrently within a single OS process.
A thread is an independent path of execution within a process.
Many threads can run concurrently within a process. There can be multiple processes inside the OS.
There are two ways to create thread in java:
- by
implementing the Runnable interface
(java.lang.Runnable) - by
extending the Thread class
(java.lang.Thread)
NOTES:
- Threads share the same address space and therefore can share both data and code
- Threads allow different tasks to be performed concurrently
- Cost of communication between the threads is low.
A thread could be in the following states:
NEW
– The thread is created, but not startedRUNNABLE
– either running or ready for execution (but it's waiting for resource allocation)BLOCKED
– waiting to acquire a monitor lock to enter or re-enter a synchronized block/methodWAITING
– waiting for some other thread to perform a particular action without any time limitTIMED_WAITING
– waiting for some other thread to perform a specific action for a specified periodTERMINATED
– has completed its execution (normally or with an exception)
Here is an example of using Threads in Java using the "extends Thread" method (the "implements Runnable" method is similar):
package threads.java.example;
class PrintValues {
static void printValues(String threadName){
for (int i = 1; i < 12; i++) {
System.out.println("printValues ---> " + i + " >>> FROM : "+threadName);
}
}
}
package threads.java.example;
public class ThreadClass extends Thread {
private Thread thread;
private String threadName;
ThreadClass( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
PrintValues printValues = new PrintValues();
System.out.println(threadName + " is running ...");
printValues.printValues(threadName);
System.out.println( threadName + " has been finished.");
}
public void start () {
System.out.println("Start " + threadName );
if (thread == null) {
thread = new Thread (this, threadName);
thread.start ();
}
}
}
package threads.java.example;
public class ThreadsInJavaExample {
public static void main(String args[]) {
ThreadClass T1 = new ThreadClass("Thread A");
T1.start();
ThreadClass T2 = new ThreadClass("Thread B");
T2.start();
}
}
And here is the result of the execution: