文档章节

并发编程实战 2.1. 使用synchronized实现同步

火犀牛
 火犀牛
发布于 2016/05/12 17:22
字数 1343
阅读 4
收藏 0
点赞 2
评论 0

如果一个对象的方法已用synchronized关键字声明,那么只有一个线程被允许访问它。如果其他线程想要访问这个对象的其他方法,它将被挂起,直到第一个线程执行完正在执行的方法。

静态方法则有不同的行为。用synchronized声明的静态方法,同时只能被一个线程访问,但是其他线程可以访问这个对象的非静态方法。会造成数据不一致的错误。

范例:两个线程:银行存钱,公司取钱;一个实体类:账户,并带有存钱与取钱的方法。

账户:

package com.rr.concurrent.chapter2.recipe1.test;

import java.util.concurrent.TimeUnit;

/**
 * Created by isaac_gu on 2016/5/12.
 */
public class Account {
    private int balance;

    public Account(int balance) {
        this.balance = balance;
    }

    public int getBalance() {
        return balance;
    }

    public void setBalance(int balance) {
        this.balance = balance;
    }

    public synchronized void saveMoney(int amount) {
        int temp = balance;
        try {
            TimeUnit.MILLISECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        temp += amount;
        balance = temp;
        System.out.println("saveMoney:" + balance);
    }

    public synchronized void drawMoney(int amount) {
        int temp = balance;
        try {
            TimeUnit.MILLISECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        temp -= amount;
        balance = temp;
        System.out.println("drawMoney:" + balance);
    }
}

银行:

package com.rr.concurrent.chapter2.recipe1.test;

/**
 * Created by isaac_gu on 2016/5/12.
 * 银行负责存钱
 */
public class Bank implements Runnable {

    private Account account;

    public Bank(Account account) {
        this.account = account;
    }

    @Override
    public void run() {
        for (int i = 0, len = 100; i < len; i++) {
            account.saveMoney(1000);
        }
    }
}

公司:

package com.rr.concurrent.chapter2.recipe1.test;

/**
 * Created by isaac_gu on 2016/5/12.
 * 公司负责取钱
 */
public class Company implements Runnable {
    private Account account;

    public Company(Account account) {
        this.account = account;
    }

    @Override
    public void run() {
        for (int i = 0, len = 100; i < len; i++) {
            account.drawMoney(1000);
        }
    }
}

测试:

package com.rr.concurrent.chapter2.recipe1.test;

/**
 * Created by isaac_gu on 2016/5/12.
 * 范例:两个线程:银行存钱,公司取钱;一个实体类:账户,并带有存钱与取钱的方法。
 */
public class Test {
    public static void main(String[] args) {
        Account account = new Account(100000);

        Thread bankThread = new Thread(new Bank(account));
        Thread companyThread = new Thread(new Company(account));

        System.out.println("START - balance: " + account.getBalance());
        bankThread.start();
        companyThread.start();

        try {
            bankThread.join();
            companyThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("END - balance: "+ account.getBalance());

    }
}

同步的结果:

START - balance: 100000
saveMoney:101000
saveMoney:102000
saveMoney:103000
saveMoney:104000
saveMoney:105000
saveMoney:106000
saveMoney:107000
saveMoney:108000
drawMoney:107000
drawMoney:106000
drawMoney:105000
drawMoney:104000
drawMoney:103000
drawMoney:102000
drawMoney:101000
drawMoney:100000
drawMoney:99000
drawMoney:98000
drawMoney:97000
drawMoney:96000
drawMoney:95000
drawMoney:94000
drawMoney:93000
drawMoney:92000
drawMoney:91000
drawMoney:90000
drawMoney:89000
drawMoney:88000
drawMoney:87000
drawMoney:86000
drawMoney:85000
drawMoney:84000
drawMoney:83000
drawMoney:82000
drawMoney:81000
drawMoney:80000
drawMoney:79000
drawMoney:78000
drawMoney:77000
drawMoney:76000
drawMoney:75000
drawMoney:74000
drawMoney:73000
drawMoney:72000
drawMoney:71000
drawMoney:70000
drawMoney:69000
drawMoney:68000
drawMoney:67000
drawMoney:66000
drawMoney:65000
drawMoney:64000
drawMoney:63000
drawMoney:62000
drawMoney:61000
drawMoney:60000
drawMoney:59000
drawMoney:58000
drawMoney:57000
drawMoney:56000
drawMoney:55000
drawMoney:54000
drawMoney:53000
drawMoney:52000
drawMoney:51000
drawMoney:50000
drawMoney:49000
drawMoney:48000
drawMoney:47000
drawMoney:46000
drawMoney:45000
drawMoney:44000
drawMoney:43000
drawMoney:42000
drawMoney:41000
drawMoney:40000
drawMoney:39000
drawMoney:38000
drawMoney:37000
drawMoney:36000
drawMoney:35000
drawMoney:34000
drawMoney:33000
drawMoney:32000
drawMoney:31000
drawMoney:30000
drawMoney:29000
drawMoney:28000
drawMoney:27000
drawMoney:26000
drawMoney:25000
drawMoney:24000
drawMoney:23000
drawMoney:22000
drawMoney:21000
drawMoney:20000
drawMoney:19000
drawMoney:18000
drawMoney:17000
drawMoney:16000
drawMoney:15000
drawMoney:14000
drawMoney:13000
drawMoney:12000
drawMoney:11000
drawMoney:10000
drawMoney:9000
drawMoney:8000
saveMoney:9000
saveMoney:10000
saveMoney:11000
saveMoney:12000
saveMoney:13000
saveMoney:14000
saveMoney:15000
saveMoney:16000
saveMoney:17000
saveMoney:18000
saveMoney:19000
saveMoney:20000
saveMoney:21000
saveMoney:22000
saveMoney:23000
saveMoney:24000
saveMoney:25000
saveMoney:26000
saveMoney:27000
saveMoney:28000
saveMoney:29000
saveMoney:30000
saveMoney:31000
saveMoney:32000
saveMoney:33000
saveMoney:34000
saveMoney:35000
saveMoney:36000
saveMoney:37000
saveMoney:38000
saveMoney:39000
saveMoney:40000
saveMoney:41000
saveMoney:42000
saveMoney:43000
saveMoney:44000
saveMoney:45000
saveMoney:46000
saveMoney:47000
saveMoney:48000
saveMoney:49000
saveMoney:50000
saveMoney:51000
saveMoney:52000
saveMoney:53000
saveMoney:54000
saveMoney:55000
saveMoney:56000
saveMoney:57000
saveMoney:58000
saveMoney:59000
saveMoney:60000
saveMoney:61000
saveMoney:62000
saveMoney:63000
saveMoney:64000
saveMoney:65000
saveMoney:66000
saveMoney:67000
saveMoney:68000
saveMoney:69000
saveMoney:70000
saveMoney:71000
saveMoney:72000
saveMoney:73000
saveMoney:74000
saveMoney:75000
saveMoney:76000
saveMoney:77000
saveMoney:78000
saveMoney:79000
saveMoney:80000
saveMoney:81000
saveMoney:82000
saveMoney:83000
saveMoney:84000
saveMoney:85000
saveMoney:86000
saveMoney:87000
saveMoney:88000
saveMoney:89000
saveMoney:90000
saveMoney:91000
saveMoney:92000
saveMoney:93000
saveMoney:94000
saveMoney:95000
saveMoney:96000
saveMoney:97000
saveMoney:98000
saveMoney:99000
saveMoney:100000
END - balance: 100000

去掉synchronized的结果

START - balance: 100000
saveMoney:101000
drawMoney:99000
saveMoney:102000
drawMoney:98000
saveMoney:103000
drawMoney:97000
saveMoney:104000
drawMoney:96000
saveMoney:105000
drawMoney:95000
saveMoney:106000
drawMoney:94000
saveMoney:107000
drawMoney:93000
saveMoney:108000
drawMoney:92000
saveMoney:109000
drawMoney:91000
saveMoney:110000
drawMoney:90000
saveMoney:111000
drawMoney:89000
drawMoney:88000
saveMoney:112000
saveMoney:113000
drawMoney:87000
saveMoney:114000
drawMoney:86000
drawMoney:85000
saveMoney:85000
saveMoney:86000
drawMoney:84000
drawMoney:83000
saveMoney:83000
saveMoney:84000
drawMoney:84000
drawMoney:83000
saveMoney:85000
saveMoney:86000
drawMoney:84000
drawMoney:85000
saveMoney:85000
saveMoney:86000
drawMoney:84000
saveMoney:83000
drawMoney:83000
drawMoney:82000
saveMoney:84000
saveMoney:85000
drawMoney:81000
saveMoney:86000
drawMoney:80000
drawMoney:79000
saveMoney:79000
drawMoney:78000
saveMoney:80000
drawMoney:77000
saveMoney:81000
drawMoney:80000
saveMoney:82000
saveMoney:83000
drawMoney:81000
drawMoney:80000
saveMoney:84000
drawMoney:79000
saveMoney:85000
drawMoney:78000
saveMoney:86000
drawMoney:77000
saveMoney:87000
drawMoney:76000
saveMoney:88000
drawMoney:75000
saveMoney:89000
drawMoney:74000
saveMoney:90000
drawMoney:73000
saveMoney:91000
drawMoney:72000
saveMoney:92000
drawMoney:71000
saveMoney:93000
drawMoney:70000
saveMoney:94000
drawMoney:69000
saveMoney:95000
drawMoney:68000
saveMoney:96000
drawMoney:67000
saveMoney:97000
drawMoney:66000
saveMoney:98000
drawMoney:65000
saveMoney:99000
drawMoney:64000
saveMoney:100000
drawMoney:63000
saveMoney:101000
drawMoney:62000
saveMoney:102000
drawMoney:61000
saveMoney:103000
drawMoney:60000
saveMoney:104000
drawMoney:59000
saveMoney:105000
drawMoney:58000
saveMoney:106000
drawMoney:57000
saveMoney:107000
drawMoney:56000
saveMoney:108000
drawMoney:55000
saveMoney:109000
drawMoney:54000
saveMoney:110000
drawMoney:53000
saveMoney:111000
drawMoney:52000
saveMoney:112000
saveMoney:113000
drawMoney:51000
drawMoney:50000
saveMoney:114000
drawMoney:49000
saveMoney:115000
saveMoney:116000
drawMoney:48000
drawMoney:47000
saveMoney:117000
drawMoney:116000
saveMoney:116000
saveMoney:117000
drawMoney:115000
saveMoney:118000
drawMoney:114000
saveMoney:115000
drawMoney:113000
saveMoney:114000
drawMoney:112000
saveMoney:113000
drawMoney:111000
drawMoney:110000
saveMoney:112000
saveMoney:111000
drawMoney:111000
saveMoney:112000
drawMoney:112000
saveMoney:113000
drawMoney:111000
saveMoney:114000
drawMoney:110000
saveMoney:115000
drawMoney:109000
drawMoney:108000
saveMoney:116000
saveMoney:117000
drawMoney:107000
saveMoney:118000
drawMoney:106000
drawMoney:105000
saveMoney:119000
saveMoney:120000
drawMoney:104000
drawMoney:103000
saveMoney:121000
drawMoney:102000
saveMoney:122000
drawMoney:101000
saveMoney:123000
drawMoney:100000
saveMoney:124000
drawMoney:99000
saveMoney:125000
saveMoney:126000
drawMoney:98000
saveMoney:127000
drawMoney:97000
saveMoney:128000
drawMoney:96000
saveMoney:129000
drawMoney:95000
saveMoney:130000
drawMoney:94000
saveMoney:131000
drawMoney:93000
saveMoney:132000
drawMoney:92000
drawMoney:91000
saveMoney:133000
drawMoney:90000
saveMoney:134000
saveMoney:135000
drawMoney:133000
drawMoney:132000
saveMoney:136000
saveMoney:137000
drawMoney:131000
drawMoney:130000
saveMoney:132000
END - balance: 132000

 

© 著作权归作者所有

共有 人打赏支持
火犀牛
粉丝 0
博文 27
码字总数 12180
作品 0
海淀
程序员
Java可重入锁学习笔记

目录 什么是可重入锁 为什么要可重入 如何实现可重入锁 有不可重入锁吗 demo代码展示 参考文章 1 . 什么是可重入锁 锁的概念就不用多解释了,当某个线程A已经持有了一个锁,当线程B尝试进入被这...

squanchao
2016/07/12
36
1
synchronized使用及实现原理

1.Synchronized的基本使用 Synchronized是Java中解决并发问题的一种最常用的方法,也是最简单的一种方法。Synchronized的作用主要有三个:(1)确保线程互斥的访问同步代码(2)保证共享变量...

梨加橙
06/28
0
0
Java 重入锁 ReentrantLock 原理分析

1.简介 可重入锁自 JDK 1.5 被引入,功能上与关键字类似。所谓的可重入是指,线程可对同一把锁进行重复加锁,而不会被阻塞住,这样可避免死锁的产生。ReentrantLock 的主要功能和 synchroniz...

Java-老刘
05/08
0
0
Java系列文章(全)

JVM JVM系列:类装载器的体系结构 JVM系列:Class文件检验器 JVM系列:安全管理器 JVM系列:策略文件 Java垃圾回收机制 深入剖析Classloader(一)--类的主动使用与被动使用 深入剖析Classloader(二...

www19
2017/07/04
0
0
设计模式-单例设计模式以及volatile关键字

单例设计模式的定义 在内存中只有一个对象实例 使用套路 构造方法私有化 使用静态方法,供外部获取对象的实例 1.饿汉式 HungrySingleton.java 特点: 在类装载的时候,就已经创建实例,而且保...

请叫我张懂
01/12
0
0
Java并发编程:同步容器

Java并发编程:同步容器   为了方便编写出线程安全的程序,Java里面提供了一些线程安全类和并发工具,比如:同步容器、并发容器、阻塞队列、Synchronizer(比如CountDownLatch)。今天我们...

eddie小英俊
2016/06/15
0
0
Java多线程学习(二)synchronized关键字(2)

系列文章传送门: Java多线程学习(一)Java多线程入门 Java多线程学习(二)synchronized关键字(1) java多线程学习(二)synchronized关键字(2) Java多线程学习(三)volatile关键字 Ja...

一只蜗牛呀
04/16
0
0
[Java并发系列] 1.Java并发机制的底层实现

在Java并发实现的机制中,大部分的容器和框架都是依赖于volatile/synchronized/原子操作实现的,了解底层的并发机制,对于并发编程会带来很多帮助 1. synchronized的应用 synchronized在多线...

Xiangdong_She
2017/11/01
0
0
说说你对synchronized同步块的了解吧?

synchronized关键字用来实现在并发编程中线程间的同步,synchronized相对于volatile关键字实现的是基于对象锁的同步,在java中每个对象都可以同步的锁。synchronized支持有实例方法、静态方法...

nj-zhangmq
2016/12/06
15
0
Java 编程之美:并发编程基础晋级篇

本文来自作者 加多 在 GitChat 上分享 「Java 并发编程之美:并发编程基础晋级篇」 编辑 | Mc Jin 借用 Java 并发编程实践中的话,编写正确的程序并不容易,而编写正常的并发程序就更难了! ...

gitchat
04/18
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

shell中的函数、shell中的数组、告警系统需求分析

shell中的函数 格式: 格式: function f_name() { command } 函数必须要放在最前面 示例1(用来打印参数) 示例2(用于定义加法) 示例3(用于显示IP) shell中的数组 shell中的数组1 定义数...

Zhouliang6
9分钟前
0
0
用 Scikit-Learn 和 Pandas 学习线性回归

      对于想深入了解线性回归的童鞋,这里给出一个完整的例子,详细学完这个例子,对用scikit-learn来运行线性回归,评估模型不会有什么问题了。 1. 获取数据,定义问题     没有...

wangxuwei
31分钟前
0
0
MAC安装MAVEN

一:下载maven压缩包(Zip或tar可选),解压压缩包 二:打开终端输入:vim ~/.bash_profile(如果找不到该文件新建一个:touch ./bash_profile) 三:输入i 四:输入maven环境变量配置 MAVEN_HO...

WALK_MAN
44分钟前
0
0
33.iptables备份与恢复 firewalld的9个zone以及操作 service的操作

10.19 iptables规则备份和恢复 10.20 firewalld的9个zone 10.21 firewalld关于zone的操作 10.22 firewalld关于service的操作 10.19 iptables规则备份和恢复: ~1. 保存和备份iptables规则 ~2...

王鑫linux
57分钟前
0
0
大数据教程(2.11):keeperalived+nginx高可用集群搭建教程

上一章节博主为大家介绍了目前大型互联网项目的系统架构体系,相信大家应该注意到其中很重要的一块知识nginx技术,在本节博主将为大家分享nginx的相关技术以及配置过程。 一、nginx相关概念 ...

em_aaron
今天
0
0
Apache Directory Studio连接Weblogic内置LDAP

OBIEE默认使用Weblogic内置LDAP管理用户及组。 要整理已存在的用户及组,此前办法是导出安全数据,文本编辑器打开认证文件,使用正则表达式获取用户及组的信息。 后来想到直接用Apache Dire...

wffger
今天
2
0
HFS

FS,它是一种上传文件的软件。 专为个人用户所设计的 HTTP 档案系统 - Http File Server,如果您觉得架设 FTP Server 太麻烦,那么这个软件可以提供您更方便的档案传输系统,下载后无须安装,...

garkey
今天
1
0
Java IO类库之BufferedInputStream

一、BufferedInputStream介绍 /** * A <code>BufferedInputStream</code> adds * functionality to another input stream-namely, * the ability to buffer the input and to * sup......

老韭菜
今天
0
0
STM 32 窗口看门狗

http://bbs.elecfans.com/jishu_805708_1_1.html https://blog.csdn.net/a1985831055/article/details/77404131...

whoisliang
昨天
0
0
Dubbo解析(六)-服务调用

当dubbo消费方和提供方都发布和引用完成后,第四步就是消费方调用提供方。 还是以dubbo的DemoService举例 -- 提供方<dubbo:application name="demo-provider"/><dubbo:registry address="z...

青离
昨天
1
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部