(1)用户可选择使用的取款方式应包含柜台和ATM取款。
(2)采用将账号的钱数定义为静态变量的方式实现该程序,每次不同的用户取钱后打印账号余额。
(3)采用线程同步的方式实现该程序,每次不同的用户取钱后打印账号余额。
静态变量方法
import java.util.Random;
class DrawMoney implements Runnable{
private static int deposit = 1000;
@Override
public void run() {
// 设置进行十轮取款
for (int i = 0;i < 10;i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (deposit > 100){
// 随机取款1~100元
int withDrawal = new Random().nextInt(100);
// 设置存款数为原存款数减去取款数
synchronized (this) {
deposit = deposit - withDrawal;
System.out.println("在" + Thread.currentThread().getName() + "取款" + withDrawal + "元,余额为" + deposit + "元。");
}
}else {
System.out.println("准备在" + Thread.currentThread().getName() + "取款,但是余额不足100元,取款失败。");
}
}
}
}
/** * @author Laccoliths * @date 2021/11/28 */
public class ThreadStatic {
public static void main(String[] args) throws InterruptedException {
DrawMoney Money = new DrawMoney();
Thread a = new Thread(Money,"柜台");
Thread b = new Thread(Money,"ATM");
a.start();
b.start();
}
}
运行结果
线程同步方法
package MoocPart11_01_01;
import java.util.Random;
/** * 共享属性 */
class resource{
private int deposit;
/** * 构造方法,初始化存款这个属性 * @param deposit */
public resource(int deposit){
super();
this.deposit = deposit;
}
/** * 构造方法,将存款缺省为1000元 */
public resource(){
// 缺省存款为1000元
deposit = 1000;
}
/** * 设置存款数 * @param deposit */
public void setDeposit(int deposit) {
this.deposit = deposit;
}
/** * 获取存款数 * @return deposit */
public int getDeposit() {
return deposit;
}
}
/** * 取钱类 */
class GetMoney implements Runnable{
private final resource resource;
/** * 构造方法,传入resource对象 */
public GetMoney(resource resource) {
this.resource = resource;
}
@Override
public void run() {
// 设置进行十轮取款
for (int i = 0;i < 10;i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (resource.getDeposit() > 100){
// 随机取款1~100元
int withDrawal = new Random().nextInt(100);
// 设置存款数为原存款数减去取款数
synchronized (this) {
resource.setDeposit(resource.getDeposit() - withDrawal);
System.out.println("在" + Thread.currentThread().getName() + "取款" + withDrawal + "元,余额为" + resource.getDeposit() + "元。");
}
}else {
System.out.println("准备在" + Thread.currentThread().getName() + "取款,但是余额不足100元,取款失败。");
}
}
}
}
/** * @author Laccoliths * @date 2021/11/27 */
public class ThreadSyn {
public static void main(String[] args) throws InterruptedException {
resource resource = new resource();
GetMoney getMoney = new GetMoney(resource);
Thread a = new Thread(getMoney,"柜台");
Thread b = new Thread(getMoney,"ATM");
a.start();
b.start();
}
}
运行结果
上一篇
下一篇