JAVA存取对象属性时,如果开程多线程,记得对相关存取方法作原子化操作定义

最显著的应用当然是银行存款和取款,不要存在存取数字和实际发生不一样的情况。

synchronized关键字。
class BankAccount {
    private int balance = 100;
    public int getBalance() {
        return balance;
    }
    public void withdraw(int amount) {
        balance = balance - amount;
    }
}
public class RyanAndMonicaJob implements Runnable {
    private BankAccount account = new BankAccount();

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        RyanAndMonicaJob theJob = new RyanAndMonicaJob();
        Thread one = new Thread(theJob);
        Thread two = new Thread(theJob);
        one.setName("Ryan");
        two.setName("Monica");
        one.start();
        two.start();

    }
    public void run() {
        for (int x = 0; x < 10; x++) {
            makeWithdrawal(10);
            if (account.getBalance() < 0) {
                System.out.println("Overdrawn!");
            }
        }
    }
    private synchronized void makeWithdrawal(int amount) {
        if (account.getBalance() >= amount) {
            System.out.println(Thread.currentThread().getName() + " is about to withdraw");
            try {
                System.out.println(Thread.currentThread().getName() + " is going to sleep");
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " woke up.");
            account.withdraw(amount);
            System.out.println(Thread.currentThread().getName() + " completes the withdrawl");
        } else {
            System.out.println("Sorry, not enough for " + Thread.currentThread().getName());
        }

    }

}

Ryan is about to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is about to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is about to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is about to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is about to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is about to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is about to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is about to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is about to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Ryan is about to withdraw
Ryan is going to sleep
Ryan woke up.
Ryan completes the withdrawl
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica
Sorry, not enough for Monica

时间: 2024-08-29 00:36:39

JAVA存取对象属性时,如果开程多线程,记得对相关存取方法作原子化操作定义的相关文章

java中对象多态时成员变量,普通成员函数及静态成员函数的调用情况

/* 样例1: class Parent{ int num = 3; } class Child extends Parent{ int num = 4; } */ /* 样例2: class Parent{ } class Child extends Parent{ int num = 4; } */ /* 样例3: class Parent{ void show(){ System.out.println("Parent Show!"); } } class Child exten

java bean 对象属性复制框架BeanMapping-01-入门案例

项目简介 Bean-Mapping 用于 java 对象属性赋值. 项目中经常需要将一个对象的属性,赋值到另一个对象中. 常见的工具有很多,但都多少不够简洁,要么不够强大. 特性 支持对象属性的浅拷贝 变更日志 变更日志 快速开始 准备 JDK1.8 及其以上版本 Maven 3.X 及其以上版本 maven 项目依赖 <dependency> <groupId>com.github.houbb</groupId> <artifactId>bean-mapp

java获取对象属性类型、属性名称、属性值

因为项目需要用到,于是简单封装了一些常用的操作: [java] view plaincopy /** * 根据属性名获取属性值 * */ private Object getFieldValueByName(String fieldName, Object o) { try { String firstLetter = fieldName.substring(0, 1).toUpperCase(); String getter = "get" + firstLetter + field

java 根据对象属性排序

在项目中经常会遇到这杨的情况,在数据中取到的 一个list集合我们需要这个集合是按我们想要的顺序排列 当然你说这可以用数据库order by 就能搞定,ok我们说的用java代码.若你已经选择要使用数据库了请绕行! 好吧居然你选择了往下继续OK 就进入代码吧, ok之前我遇到这样的需求的时候为了简单也使用过数据库来做,后来数据库查询的sql越来越复杂之后就想用j ava来帮帮数据库减轻一下压力."毕竟,压力来自轮胎,就算跳到250P,FC 的马力还是太大,难以做到最大限度的飘逸". 我

java中对象属性可以是另外一个对象或对象的参考

7.对象的属性可以是另外一个对象或对象的参考 (视频下载) (全部书籍) 通过这种方法可以迅速构建一个比较大的系统. 本章源码 class Motor {    Light[] lights;    Handle left, right;    KickStart ks;    Motor() {        lights = new Light[2];        lights[0] = new Light();        lights[1] = new Light();       

javascript原型对象与实例对象属性

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getS

spring学习——注入静态对象属性

spring注入静态对象属性时,因为虚拟机类加载问题,直接在属性上使用@Autowired 是不可以的.需要在属性对应的set方法上@Autowired,并且,set方法不能定义为static. 1.创建静态对象属性对应的类 package com.bluej.springj.service.impl; import org.springframework.stereotype.Service; import com.bluej.springj.service.LogService; @Serv

实现对象属性的lazy-loading(延迟加载)

一.延迟加载器LazyLoader作用:       说到延迟加载,应该经常接触到,尤其是使用Hibernate的时候,本篇将通过一个实例分析延迟加载的实现方式.LazyLoader接口继承了Callback,因此也算是CGLib中的一种Callback类型. 二.示例:        首先定义一个实体类LoaderBean,该Bean内有一个需要延迟加载的属性对象PropertyBean. LoaderBean.java: public class LoaderBean { private S

js对象属性的命名规则

JS标识符的命名规则,即变量的命名规则: 标识符只能由字母.数字.下划线和'$'组成 数字不可以作为标识符的首字符 对象属性的命名规则 通过[]操作符为对象添加属性时,属性名称可以是任何字符串(包括只包含空格的字符串和空字符串): 通过.操作符为对象添加属性时,属性名称必须是合法的标识符名称: 如果属性名包含非法的标识符字符,则只能采用obj["propertyName"]的形式: 如果属性名是合法的标识符,读取时即可以采用obj.propertyName,也可以采用obj["