当前位置:网站首页>模拟线程通信

模拟线程通信

2022-07-06 23:09:00 洋啊桑815

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();
    }
}

原网站

版权声明
本文为[洋啊桑815]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_66344432/article/details/125601903