Pterson算法解决操作系统的互斥现象,示例代码如下:
package Test;
public class Peterson {
public static void main(String[] args) throws InterruptedException {
//1.创建了一个账户,初始2000;
Account1 account = new Account1(2000);
//2.创建两个线程
ATMThread1 atm = new ATMThread1(account);
EPayThread1 epay = new EPayThread1(account);
//3.并发执行两个进程
atm.start();
epay.start();
atm.join();
epay.join();
System.out.println("2秒后显示余额:");
Thread.sleep(2000);
account.printBalance();
}
}
class GlobalSRC1{
public static volatile int turn = 0;
public static volatile boolean[] flag = new boolean[] {false,false};
}
//p0
class ATMThread1 extends Thread{
private Account1 account;
public ATMThread1(Account1 account) {
this.account=account;
}
public void run() {
//调用widthdraw()就是访问临界资源的代码
GlobalSRC1.flag[0]=true;//表示自己想进
GlobalSRC1.turn=1;//但是先让给p1
while(GlobalSRC1.flag[1]==true && GlobalSRC1.turn==1);//判断p1在不在,在就不做任何事,不在就执行自己
//--------Critical Section Start-----
int result = account.widthdraw(1600);//ATM取款1600
//--------Critical Section End-----
GlobalSRC1.flag[0]=false;//完成后状态设置为false
if(result==-1) {
System.out.println("ATM取款失败");
}else{
System.out.println("ATM取款成功取出"+result+"元");
}
}
}
//p1
class EPayThread1 extends Thread{
private Account1 account;
public EPayThread1(Account1 account) {
this.account=account;
}
public void run() {
//调用ePay()就是访问临界资源的代码
GlobalSRC1.flag[1]=true;//表示自己想进
GlobalSRC1.turn=0;//但是先让给p0
while(GlobalSRC1.flag[0]==true && GlobalSRC1.turn==0);//判断p0在不在,在就不做任何事,不在就执行自己
//--------Critical Section Start-----
int result = account.ePay(800);
//--------Critical Section End-----
GlobalSRC1.flag[1]=false;//完成后状态设置为false
if(result==-1) {
System.out.println("网银支付失败");
}else{
System.out.println("网银支付成功,支付"+result+"元");
}
}
}
class Account1{
private int balance;
public void printBalance() {
System.out.println("账户余额:"+this.balance);
}
public Account1(int amount) {
this.balance = amount;
}
//通过ATM取款
public int widthdraw(int amount) {
if(amount<=0 || amount>balance) {
return -1;
}else {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
balance = balance-amount;
return amount;
}
}
//通过网银支付
public int ePay(int amount) {
if(amount<=0 || amount>balance) {
return -1;
}else {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
balance = balance-amount;
return amount;
}
}
}