加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 07:21:10 所属栏目:Java 来源:网络整理
导读:账号提钱、存钱实例方法 public class Account { private int balance; private int maxBalance; public Account( int balance) { this .balance= balance; } // 同步方法 取钱 public synchronized void transferOut( int money) { // 线程同步 // synchron

 账号提钱、存钱实例方法

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

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读