欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java 线程同步方法执行与唤醒实例

程序员文章站 2023-10-28 22:46:28
账号提钱、存钱实例方法 测试方法 ......

 账号提钱、存钱实例方法

public class account {
    private int balance;
    private int maxbalance;
    public account(int balance)
    {
        this.balance=balance;
    }
    //同步方法  取钱 
    public synchronized void transferout(int money) {
         //线程同步 
        //synchronized(this) {
        string theadname=thread.currentthread().getname();
        if(balance>money) {
            try {
                thread.sleep(1);
            }catch(interruptedexception e ){
                e.printstacktrace();
            }
            balance=balance-money;
            system.out.println(theadname+"转走:"+money+",余额:"+balance);
        }else {
            system.out.println(thread.currentthread().getname()+"余额不足");
        }
//        }
    }
    
       //同步方法  线程等待  存钱
        public synchronized void save(int money) {
            while(balance+money>maxbalance) {
                try {
                    this.wait(); //线程等待
                } catch (interruptedexception e) {
                    // todo auto-generated catch block
                    e.printstacktrace();
                }
            }
            string theadname=thread.currentthread().getname();
            balance=balance+money;
            system.out.println( "save "+money+"元"+" balance:"+balance);
            this.notifyall();//唤醒其它线程
            
        }
          //同步方法  线程等待  存钱
        public synchronized void withdraw(int money) {
            while(money>balance) {
                try {
                    this.wait(); //线程等待
                } catch (interruptedexception e) {
                    // todo auto-generated catch block
                    e.printstacktrace();
                }
            }
        
            balance=balance-money;
            system.out.println( "take "+money+"元"+" balance:"+balance);
            this.notifyall();//唤醒其它线程
            
        }
}

  测试方法

public class test {

    public static void main(string[] args) {
         
        
        account account2=new account(8000);
        thread t1=new thread(new takemoney(account2),"son1");
        thread t2=new thread(new takemoney(account2),"son2");
        t1.start();
        t2.start();
    }

}