一个程序就是一个进程
多线程指在同一个程序中的多个应用和功能
LearnThreadSync.java 代码
package ThreadSync;
public class LearnThreadSync {
public static void main(String[] args) {
BankAccount account=new BankAccount();
Thread husband=new BankThread(account);
Thread wife=new BankThread(account);
husband.start();
wife.start();
}
}
LearnThreadSync.png
BankAccount.java 代码
package ThreadSync;
public class BankAccount {
private double balance=1000;
public boolean deposit(double newAdd){
if(newAdd<=0){
return false;
}else{
synchronized (this) {
System.out.println("当前余额为"+balance);
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
balance=balance+newAdd;
System.out.println("您的余额为"+balance);
}
return true;
}
}
}
BankAccount.png
BankThread.java 代码
package ThreadSync;
public class BankThread extends Thread {
private BankAccount bankAccount;
public BankThread(BankAccount account){
bankAccount=account;
}
@Override
public void run() {
bankAccount.deposit(200);
}
}
BankThread.png
作者: 聪聪工作室
业务合作: 18758171751
微信: 18758171751
Email: 1099749430@qq.com聪聪工作室---Java---独家制作
版权所有,盗版必究!
网友评论