As the word state this is the point where programe execution is not possible. This generally occured in 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.
As both threads are waiting for each other to release the lock, the condition reached is called deadlock.
public class TestDeadlockExample1 {
public static void main(String[] args) {
final String resource1 = "This is Resource1";
final String resource2 = "This is Resource2";
// thread1 tries to lock resource1 then resource2
Thread thread1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked Resource 1");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource2) {
System.out.println("Thread 1: locked Resource 2");
}
}
}
};
// thread2 tries to lock resource2 then resource1
Thread thread2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked Resource 2");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource1) {
System.out.println("Thread 2: locked Resource 1");
}
}
}
};
thread1.start();
thread2.start();
}
}
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.
As both threads are waiting for each other to release the lock, the condition reached is called deadlock.
public class TestDeadlockExample1 {
public static void main(String[] args) {
final String resource1 = "This is Resource1";
final String resource2 = "This is Resource2";
// thread1 tries to lock resource1 then resource2
Thread thread1 = new Thread() {
public void run() {
synchronized (resource1) {
System.out.println("Thread 1: locked Resource 1");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource2) {
System.out.println("Thread 1: locked Resource 2");
}
}
}
};
// thread2 tries to lock resource2 then resource1
Thread thread2 = new Thread() {
public void run() {
synchronized (resource2) {
System.out.println("Thread 2: locked Resource 2");
try { Thread.sleep(100);} catch (Exception e) {}
synchronized (resource1) {
System.out.println("Thread 2: locked Resource 1");
}
}
}
};
thread1.start();
thread2.start();
}
}
No comments:
Post a Comment