利用Thread或Runnable实现一个多用户的银行取款程序。为了保证多个用户在对同一账户取钱时数据的一致性,可通过定义静态变量和线程同步两种方式实现。要求:
静态变量方法
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(); } }
运行结果

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/205790.html原文链接:https://javaforall.net
