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


     账号提钱、存钱实例方法

    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();
        }
    
    }
  • 相关阅读:
    python 合并 Excel 单元格
    python 设置 Excel 表格的行高和列宽
    Python 用 openpyxl 模块统计 Excel 表格中的数据,以字典形式写入 py 文件
    python 打印字母阶梯和金字塔
    python 用 openpyxl 读取 Excel 表格中指定的行或列
    Python 的 filter() 函数
    Python 的 map() 函数
    python 之 range() 函数
    python 的 reduce() 函数
    python 之 lambda 函数
  • 原文地址:https://www.cnblogs.com/personblog/p/11703760.html
Copyright © 2020-2023  润新知