Showing posts with label Dead lock. Show all posts
Showing posts with label Dead lock. Show all posts

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

techguruspeaks

  Core Java programming Introduction to Java Java Features Writing a Simple Java Program Java Keywords and Comments Variables, Identifiers ...