Deadlock Between Two Threads Example in Java
On this page (9sections)
Introduction
DeadLock Between Two Threads is a classic Java console program that demonstrates the concept with complete source code and sample output. Threads allow concurrent execution — useful for background tasks and parallel work.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
a deadlock is a situation in which two or more competing actions are each waiting for the other to finish, and thus neither ever does. a deadlock happens when two processes each within its own transaction updates two rows of information but in the opposite order.
DeadLock Between Two Threads Example Program
public class DeadLockBetweenTwoThreads {
String strone = "HAI";
String strtwo = "HELLO";
Thread t1 = new Thread("Thread One"){
public void run(){
while(true){
synchronized(strone){
synchronized(strtwo){
System.out.println(strone + strtwo);
}
}
}
}
};
Thread t2 = new Thread("Thread Two"){
public void run(){
while(true){
synchronized(strtwo){
synchronized(strone){
System.out.println(strtwo + strone);
}
}
}
}
};
public static void main(String a[]){
DeadLockBetweenTwoThreads obj = new DeadLockBetweenTwoThreads();
obj.t1.start();
obj.t2.start();
}
}
Sample Output
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HAIHELLO
HELLOHAI
HELLOHAI
HELLOHAI
HELLOHAI
HELLOHAI
HELLOHAI
HELLOHAI
HELLOHAI
HELLOHAI
HELLOHAI
HELLOHAI
When to use
Use this deadlock between two threads example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
String strone = "HAI";updates a variable used in the calculation or output. -
String strtwo = "HELLO";updates a variable used in the calculation or output. -
Thread t1 = new Thread("Thread One"){updates a variable used in the calculation or output. -
A loop repeats the block until its condition becomes false.
-
A
println/printcall writes text to the console — part of the sample output below. -
Thread t2 = new Thread("Thread Two"){updates a variable used in the calculation or output. -
A loop repeats the block until its condition becomes false.
Best Practices
- Use meaningful variable and class names that describe their purpose.
- Compile and run the program locally — modify values to see how output changes.
- Read compiler errors carefully; they usually point to the exact line to fix.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.