zoukankan      html  css  js  c++  java
  • 线程同步练习

    package lianxi1;
    class User implements Runnable{
        static Account account = new Account();
        @Override
        public void run() {
            for(int i=0;i<3;i++){
                account.deposit(1000.00);
            }
            
        }
        
    }
    class Account{
        private double balance;
        public Account(){
            
        }
        public Account(double balance) {
            super();
            this.balance = balance;
        }
        public synchronized void deposit(double num){
            try {
                Thread.currentThread().sleep(10);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            balance = balance + num; //两个线程先后唤醒,第一个线程加1000,没打印,第二个线程又加1000,
                                     //开始打印第一个线程和第二个,所以线程1和2的余额相同
            System.out.println(Thread.currentThread().getName()+"存款,账户余额:"+balance);
        }
    }
    public class TestThreadAccount {
    
        public static void main(String[] args) {
              User au = new User();
              Thread t1 = new Thread(au);
              Thread t2 = new Thread(au);
              t1.setName("顾客1");
              t2.setName("顾客2");
              t1.start();
              t2.start();
        }
    
    }
  • 相关阅读:
    delphi之动态库调用和串口通讯
    git如何使用 svn如何使用
    delphi学习笔记1
    sql
    linux连接与传输等命令
    jdbc
    list/tstringlist/tobjectlist
    SQL GRANT
    Invalidate介绍
    FORM 的创建
  • 原文地址:https://www.cnblogs.com/yjtm53/p/4161631.html
Copyright © 2011-2022 走看看