模拟线程通信

1:多个线程共同操作的共享资源:User类 含有money存款,以及存钱与取钱的方法


public class User {
    private double money;

    public User() {
    }

    public User(double money) {
        this.money = money;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    /***
     * 存钱的方法
     * @param money
     */
    public synchronized void updateMoney(Double money){
        try {
            System.out.println(Thread.currentThread()+"进来了");
            Thread.sleep(2000);
            if(this.money==0){
                this.money+=money;
                System.out.println(Thread.currentThread()+"存钱"+money);
                this.notifyAll();
                this.wait();
            }else{
                this.notifyAll();
                this.wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    /***
     * 取钱的方法的方法
     * @param v
     */
    public synchronized void deleteMoney(double v) {
        try {
            System.out.println(Thread.currentThread()+"进来了");
            Thread.sleep(2000);
            if(this.money>=v){
                this.money-=v;
                System.out.println(Thread.currentThread()+"取钱"+v);
                this.notifyAll();
                this.wait();
            }else{
                this.notifyAll();
                this.wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

创建两个线程:存款线程与取款线程

//取钱
public class GetThread extends Thread{
    private User user;

    public GetThread(User user,String name) {
        super(name);
        this.user = user;
    }
    @Override
    public void run(){
        while (true) {
            user.deleteMoney(1000.0);
        }
    }
}
//存钱
public class SetThread extends Thread {
    private User user;

    public SetThread(User user,String name) {
        super(name);
        this.user = user;
    }
    @Override
    public void run(){
        while (true) {
            user.updateMoney(10000.0);
        }
    }
}

主方法:



public class TestDamo {
    
    public static void main(String[] args) {
        User user=new User(1000);
        new GetThread(user,"小明1").start();
        new GetThread(user,"小明2").start();

        new SetThread(user,"小红1").start();
        new SetThread(user,"小红2").start();
        new SetThread(user,"小红3").start();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值