Deadlock.java
/*
* Copyright@ 2011 www.egtry.com
*/
package egtry.thread;
/**
Potential deadlock occurs if
1. Two or more shared resources
2. Thead1 hold resource1 and need resource 2, and Thread2 hold resource2 and need resource 1
*
*/
public class Deadlock extends Thread {
private Account from;
private Account to;
private int amount;
public static void main(String[] args) {
Account a1=new Account(100);
Account a2=new Account(200);
Deadlock t1=new Deadlock(a1,a2,10);
Deadlock t2=new Deadlock(a2,a1,20);
t1.start();
t2.start();
System.out.println("Done");
}
public Deadlock(Account from, Account to, int amount) {
this.from=from;
this.to=to;
this.amount=amount;
}
@Override
public void run() {
synchronized (from) {
synchronized (to) {
from.balance -=amount;
to.balance +=amount;
}
}
}
public static class Account {
public int balance;
public Account(int balance) {
this.balance=balance;
}
}
}