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

Inter thread Communication

wait() -causes current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object

public void notify() -Wakes up a single thread that is waiting on this object's monitor.

public void notifyAll() -Wakes up all the threads that called wait( ) on the same object.




class student extends Thread {
int amount = 1000;

void withdraw ( int amount ) {
synchronized (this) {
System.out.println("Withdrawing..." + amount);

if (this.amount < amount) {
System.out.println("Low balance...." + this.amount);

try {
wait();
} catch (Exception e) {
}
}//if ends
this.amount = this.amount - amount;
System.out.println("withdraw completed " + amount);
System.out.println("Balance" + this.amount);
}
}

synchronized void deposit ( int amount ) {
System.out.println("going to deposit..." + amount);
this.amount = this.amount + amount;
System.out.println("update balance deposit completed... " + this.amount);
notify();
}
} // student ends


class interth {
public static void main ( String[] args ) {
student s = new student();
new Thread() {
public void run () {
s.withdraw(1500);
}
}.start();
new Thread() {
public void run () {
s.deposit(1000);
}
}.start();

}
}

Output:
Withdrawing...1500
Low balance....1000
going to deposit...1000
update balance deposit completed... 2000
withdraw completed 1500
Balance500

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...