Transaction class
public class Transaction {
private Object accountA = new Object();
private Object accountB = new Object();
public void transferA2B(){
synchronized (accountA) {
System.out.println("lock for A held in A2B");
try { // sleep given to force deadlock
Thread.sleep(1000);
} catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace();
}
synchronized (accountB) {
System.out.println("lock for B held in A2B");
}
}
}
public void transferB2A(){
synchronized (accountB) {
System.out.println("lock for B held in B2A");
try { // sleep given to force deadlock
Thread.sleep(1000);
} catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace();
} synchronized (accountA) {
System.out.println("lock for A held in B2A");
}
}
}
}
Two Threads A and B will call the individual methods of Transaction from the run method, so I am avoiding the code snippets for the threads
The DeadloackTest class
public class DeadlockTest {
public static void main(String[] args) {
Transaction tran = new Transaction();
Thread a = new Thread(new ThreadA(tran));
Thread b = new Thread(new ThreadB(tran));
a.start(); b.start();
}}
No comments:
Post a Comment