当前位置: 移动技术网 > IT编程>开发语言>Java > java 线程同步方法执行与唤醒实例

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

2019年10月19日  | 移动技术网IT编程  | 我要评论

 账号提钱、存钱实例方法

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

}

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网