search
HomeJavajavaTutorialHow to implement a withdrawal applet with java multi-threading

1. Create java classes

How to implement a withdrawal applet with java multi-threading

Three java classes are created here. The first Account class is used to encapsulate each item in the account. kind of information; the third DrawThread class is used to implement the thread body; the second class mainly encapsulates the main function

2, Account class

public class Account {
    //封装账户编号,账户余额和两个成员变量
    private String accountNo;
    private double balance;

    public Account(){};
    public Account(String accountNo,double balance){
        this.accountNo=accountNo;
        this.balance=balance;
    }

    public void setAccountNo(String accountNo)
    {
        this.accountNo=accountNo;
    }
    public void setBalance(double balance){
        this.balance=balance;
    }

    public String getAccountNo(){
        return accountNo;
    }
    public double getBalance(){
        return balance;
    }

    public int hashCode(){
        return accountNo.hashCode();
    }

    public boolean equals(Object obj){
        if(this==obj){
            return true;
        }
        if (obj!=null&&obj.getClass()==Account.class){
            Account target=(Account)obj;
            return target.getAccountNo().equals(accountNo);
        }
        return false;
    }

}

3 , DrawThread class

public class DrawThread extends Thread {
    //模拟用户账户
    private Account account;
    //当前取钱线程所希望的取钱数
    private double drawAmount;

    public DrawThread(String name, Account account, double drawAmount) {
        super(name);
        this.account = account;
        this.drawAmount = drawAmount;
    }

    //当多个线程修改同一个共享数据时,将涉及数据安全问题
    public void run() {
        //使用account作为同步监视器,任何线程进入下面同步代码块之前
        //必须先获得对account账户的锁定——其他线程无法获得锁,也就无法修改它
        synchronized (account) {
            if (account.getBalance() >= drawAmount) {
                //吐出钞票
                System.out.println(getName() + "取钱成功!吐出钞票:" + drawAmount);
        /*
        try {
           Thread.sleep(1);
           }catch (InterruptedException ex)
        {
            ex.printStackTrace();
        }
        */
                //修改余额
                account.setBalance(account.getBalance() - drawAmount);
                System.out.println("\t余额为:" + account.getBalance());
            } else {
                System.out.println(getName() + "取钱失败!余额不足!");
            }
        }
    }
}

4, DrawTest class

public class DrawTest {
    public static void main(String[] args){
        //创建一个账户
        Account acct=new Account("1234567",1000);
        //模拟两个线程对同一个账户取钱
        new DrawThread("jack",acct,800).start();
        new DrawThread("rose",acct,800).start();
    }
}

Running result:

How to implement a withdrawal applet with java multi-threading

The above program One thing to note is the use of synchronized code blocks. It can solve the synchronization safety problem of the run() method. For example, when two threads send requests at the same time, an exception may occur.

Synchronization code block:

synchronized (obj){
//需要执行的代码
}

If we remove the run() method Continue to run the synchronization code block in

Account acct=new Account("1234567",1000);
new DrawThread("jack",acct,800).start();
new DrawThread("rose",acct,800).start();

(the bank account has a total of 1,000 yuan, Jack and rose respectively withdraw money from the same account)

Running result:

How to implement a withdrawal applet with java multi-threading

The above is the detailed content of How to implement a withdrawal applet with java multi-threading. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools