/**
* 创建一个账号类
*/
public class Account {
private String accountName;
private int price;
public Account(String accountName, int price) {
this.accountName = accountName;
this.price = price;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
/*
转账账号减钱
*/
public void delete(int money){
this.price -= money;
}
/*
收款账号加钱
*/
public void add(int money){
this.price += money;
}
}
/**
* 实现一个多线程
*/
public class TransferAccount implements Runnable{
private Account fromAccount;
private Account toAccount;
private int amount;
public TransferAccount(Account fromAccount, Account toAccount, int amount) {
this.fromAccount = fromAccount;
this.toAccount = toAccount;
this.amount = amount;
}
@Override
public void run() {
while(true){
synchronized (fromAccount){
synchronized (toAccount){
if(fromAccount.getPrice() >= amount){
fromAccount.delete(amount);
toAccount.add(amount);
System.out.println(fromAccount.getAccountName()+"------"+fromAccount.getPrice());
System.out.println(toAccount.getAccountName()+"------"+toAccount.getPrice());
}
}
}
}
}
}
/**
* 测试死锁
*/
public class Test {
public static void main(String[] args) {
Account from = new Account("张三",100);
Account to = new Account("李四",50);
Thread a = new Thread(new TransferAccount(from,to,1));
Thread b = new Thread(new TransferAccount(to,from,3));
a.start();
b.start();
}
}
破坏死锁例子(占有且等待条件)
/**
* 创建一个管理角色防止占有且等待
*/
public class Allcator {
private List<Object> list = new ArrayList<>();
/**
* 申请锁资源
* @param from
* @param to
* @return
*/
synchronized boolean apply(Object from,Object to){
if(list.contains(from) || list.contains(to)){
return false;
} else {
list.add(from);
list.add(to);
return true;
}
}
/**
* 释放锁资源
* @param from
* @param to
*/
synchronized void free(Object from,Object to){
list.remove(from);
list.remove(to);
}
}
/**
* 测试破坏死锁
*/
public class Test {
public static void main(String[] args) {
Account from = new Account("张三",100);
Account to = new Account("李四",50);
Allcator allcator = new Allcator();//统一分配锁
Thread a = new Thread(new TransferAccount(from,to,1,allcator));
Thread b = new Thread(new TransferAccount(to,from,3,allcator));
a.start();
b.start();
}
}