Saturday, December 17, 2022

Dead lock in java

 Deadlock in java is a part of multithreading. Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called deadlock. – deadlock.java


package LabCommon;

class deadlock {
public static void main ( String[] aa ) {
final String a = "a";
final String b = "b";

Thread t1 =
new Thread() {
public void run () {
synchronized (a) {
System.
out.println("thread1: locked a");
try {
Thread.
sleep(100);
}
catch (Exception e) {
}
synchronized (b) {
System.
out.println("thread1: locked b");
}
}
}
};

Thread t2 =
new Thread() {
public void run () {
synchronized (b) {
System.
out.println("Thread 2: locked b");
try {
Thread.
sleep(100);
}
catch (Exception e) {
}

synchronized (a) {
System.
out.println("Thread 2: locked a");
}
}
}
};
t1.start();
t2.start();
}
}





Output:
thread1: locked a Thread 2: locked b

No comments:

Post a Comment

Programming in Java (Semester-5)

  Programming in Java (Semester-5) Syllabus Unit I Unit II Unit III Practical Question Bank Java Practical Programs Java Important Topics Qu...