Threads in Java
like labour
Introduction
A Thread is a small set of instructions designed to be scheduled and executed by the CPU independently of the parent process. To run the process in another thread, you the support of both the operating system and the process. When you create another thread, JVM communicates OS to create a new thread which can then run on the "multi-threaded CPU". Well this article isn't about explain threads, it's about how you can play with them in Java
Threads are everywhere by default
When write and run a simple java program, JVM is creating the main thread for you to print hello world
public class Solution {
public static void main(String[] args) throws Exception {
System.out.println("hello world");
throw new Exception();
}
}
// output :
hello world
Exception in thread "main" java.lang.Exception
at Solution.main(Solution.java:5)If you read the error message carefully, it says Exception in thread "main" , hence proved ...
How to create a thread ?
Well, cuz Java is an Object-Oriented Language, everything is wrapped in OOP concepts. To run a method of some class in-parallel
Extend the class from the Thread class
Create a method overriding the run() method
This run method is what is executed separately in a thread.
Here is an example :
To run two thread of seperate class
When you call the .start() method, it will execute the run() method in a seperate thread.
Well becuase java doesnt support mulitple inheritanc, if you ever have to inherit from another class, you wont be able to do it. To overcome this limitation/feature we can implement the Runnable interface
The only difference here is you implement the Runnable interface, create objects of the Thread class passing the objects implementing Runnable, and call the start method on the thread object, which in--return executes the .run() methods.
Properties of a Thread Class
getName() : Stringgets you the name of the threadsetName(String name): set name of a thread
isAlive() : Booleanwhether the thread is active or notgetId() : Longget the execution id of the threadgetPriority(): get the priority of threadsetPriority(int num): on a scale of 1-10Predefined ENUMS
Thread.MAX_PRIORITY= 10Thread.MIN_PRIORITY= 1Thread.NORM_PRIORITY= 5
For more, refer to documentation : https://download.java.net/java/early_access/loom/docs/api/java.base/java/lang/Thread.html
Joining Threads
When you spin off a thread, you also have to wait for it to finish its task before moving on to avoid errors/exception
Synchronizing Threads
thread sync happens at object level, not at method level (even tho marked at method), applicable for methods marked with sync
use synchronized on blocks to avoid wait times
by synchronized(this) to lock the current object
by synchronized(x) to pass an object and lock it
by synchronized(X.class) to get class level lock
Thread interrupt
Thread Yield
Java Thread yield() method : The yield() method of thread class causes the currently executing thread object to temporarily pause and allow other threads to execute.
Inter thread communication methods
wait
notify
notifyAll()
Important Points
using
runnableis better because when you extend fromthreadyou cannot inherit from other class
Limitations of using thread and runnable
time consuming : creation and management of thread
poor resource management
not robust : cannot handle scale
ExecutorService
example :
Future & Callable
example
Last updated
Was this helpful?