There are situations when programs become deadlocked when each thread is waiting on a resource that cannot become available. The simplest form of deadlock is when two threads are each waiting on a resource that is locked by the other thread. Since each thread is waiting for the other thread to relinquish a lock, they both remain waiting forever in the Blocked-for-lock-acquisition state. The threads are said to be deadlocked.
Thread t1 at tries to synchronize first on string o1 and then on string o2. The thread t2 does the opposite. It synchronizes first on string o2 then on string o1. Hence a deadlock can occur as explained above.
Below is a program that illustrates deadlocks in multithreading applications
public class DeadLockExample {
String o1 = "Lock ";
String o2 = "Step ";
Thread t1 = (new Thread("Printer1") {
public void run() {
while (true) {
synchronized (o1) {
synchronized (o2) {
System.out.println(o1 + o2);
}
}
}
}
});
Thread t2 = (new Thread("Printer2") {
public void run() {
while (true) {
synchronized (o2) {
synchronized (o1) {
System.out.println(o2 + o1);
}
}
}
}
});
public static void main(String[] args) {
DeadLockExample dLock = new DeadLockExample();
dLock.t1.start();
dLock.t2.start();
}
}
1 comments:
Did you know that you can make cash by locking selected pages of your blog / website?
Simply join AdscendMedia and run their Content Locking tool.
Post a Comment