synchronized一个(二)
今天遇到了一个关于synchronized的一个问题,关于其持有锁的问题。这个问题以前是有看过相关文章的,但是一直没有记录,今天大概记录一下当前的认知。
对于静态方法,synchronized的使用的锁实际上是以Class对象作为锁,对于非静态方法,持有的锁为方法所在的对象。可能有点难以理解,但是,仔细想想,静态方法是类级别的,而非静态方法属于对象级别的。这样或许好理解一下。
关于synchronized的常规用法
同步控制块。进入此段代码前,必须得到syncObject对象的锁,如果其他线程正在持有这个锁,那么就得等到这个线程释放以后,才能进入临界区。
synchronized(syncObject){
//处理逻辑
}
亦或使用其修饰整改方法,这个时候,就需要注意到开头说的锁的问题了。对于不同级别的方法,所持有的锁是不同的。
synchronized fun(){
//处理逻辑
}
下面我们,通过demo来说这个情况。注释代码,说明了静态方法与非静态方法使用不同的锁。三个线程并发,为了说明即使在同一个对象当中,也必须使用相同的对象锁,synchronized才能确保临界区同一个时刻只能被一个线程访问。结果中先输出fun2表明线程2并没有因线程1持有当前demo对象的锁而被阻塞,但是线程3却被阻塞了。
package com.woniu.test.concurrency; import java.util.HashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit; public class TestSynchronized { public static void main(String[] args) throws InterruptedException {
// ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
// executor.scheduleAtFixedRate(new Demo(), 1, 2, TimeUnit.SECONDS);
//
// while(true) {
// System.out.println(System.currentTimeMillis() + ", woniu id is " + Demo.getMap().get("woniu"));
// Thread.sleep(1000);//这里的延迟会因updateMap持有相同的锁,导致延迟的时间变得更长
// } final Demo demo = new Demo(); new Thread(new Runnable() { public void run() {
try {
demo.fun1();
} catch (InterruptedException e) {
e.printStackTrace();
} }
}
).start(); Thread.sleep(1000);
new Thread(new Runnable() { public void run() {
try {
demo.fun2();
} catch (InterruptedException e) {
e.printStackTrace();
} }
}
).start(); new Thread(new Runnable() { public void run() {
try {
demo.fun3();
} catch (InterruptedException e) {
e.printStackTrace();
} }
}
).start();
}
} class Demo implements Runnable { private static HashMap<String, Integer> map = new HashMap<String, Integer>();
private Object obj = new Object();
public Demo() {
map.put("woniu", 1);
} public void run() {
try {
updateMap();
} catch (InterruptedException e) {
e.printStackTrace();
}
} //如果updateMap没有使用static进行修饰,此处休息3000ms,对于主线程的while循环式不起作用的,因为两者使用的锁不一致。
public synchronized static void updateMap() throws InterruptedException {
System.out.println("begin to update");
Thread.sleep(3000);
map.put("woniu", map.get("woniu") + 1);
System.out.println("update end");
} public synchronized static HashMap<String, Integer> getMap() {
return map;
} public synchronized void fun1() throws InterruptedException {
Thread.sleep(3000);
System.out.println("this is fun1()");
} public void fun2() throws InterruptedException {
synchronized (obj) {
System.out.println("this is fun2()");
}
} public void fun3() throws InterruptedException {
synchronized (this) {
System.out.println("this is fun3()");
}
}
}
synchronized一个(二)的更多相关文章
- 二维码合成,将苹果和安卓(ios和android)合成一个二维码,让用户扫描一个二维码就可以分别下载苹果和安卓的应用
因为公司推广的原因,没有合适的将苹果和安卓(ios和android)合成一个二维码的工具. 因为这个不难,主要是根据浏览器的UA进行判断,所以就自己开发了一个网站 网站名称叫:好推二维码 https ...
- [LeetCode] Search a 2D Matrix II 搜索一个二维矩阵之二
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...
- [LeetCode] Search a 2D Matrix 搜索一个二维矩阵
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...
- ytu 1050:写一个函数,使给定的一个二维数组(3×3)转置,即行列互换(水题)
1050: 写一个函数,使给定的一个二维数组(3×3)转置,即行列互换 Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 154 Solved: 112[ ...
- 正确运用synchronized和二次判断 实现多线程安全
正确运用synchronized和二次判断 实现多线程安全,做出高效二符合预期的程序,特别是多个线程跑一个对象的时候,如下图所示: 测试代码如下: 特别注意if(shutdownRequested) ...
- [CareerCup] 11.6 Search a 2D Matrix 搜索一个二维矩阵
11.6 Given an M x N matrix in which each row and each column is sorted in ascending order, write a m ...
- [CareerCup] 13.10 Allocate a 2D Array 分配一个二维数组
13.10 Write a function in C called my2DAlloc which allocates a two-dimensional array. Minimize the n ...
- new一个二维数组
.定义一个二维数组 char **array1 array1 = new char *[x]; for(i=0;i<x;++i) array1[i] = new char[y]; ...用的时候 ...
- C语言里的指针探析——type *name[] 在函数参数里面,是一个二维指针
type *name[] 在函数参数里面声明和不在函数里面声明其实不一样. type *name[] 如果在函数参数里声明,则name 是一个二维指针,并不是一个指针数组,而如果不在函数参数里声明,则 ...
- 公司开发的APP,如何生成一个二维码,供客户下载使用
1.其实和简单,因为一般的用户使用扫一扫,大多数都是用微信自带的扫一扫工具 而,微信打开的二维码页面,会自动屏蔽apk文件,所以显然把apk的url生成一个二维码,让用户扫一扫就能直接下载,这样是行不 ...
随机推荐
- centos7 安装python3.6 及模块安装演示
目录: 下载python3.6 安装python3.6的依赖 编译安装 更改链接 更改yum脚本的python依赖 修改gnome-weaktool配置文件 修改urlgrabber配置文件 1.下载 ...
- Spark中ml和mllib的区别
转载自:https://vimsky.com/article/3403.html Spark中ml和mllib的主要区别和联系如下: ml和mllib都是Spark中的机器学习库,目前常用的机器学习功 ...
- soapUi下载
http://dl.eviware.com/list_soapui2.html http://smartbearsoftware.com/repository/eviware/jars/
- Windows Server 2008 R2(X64) MSDN镜像简体中文版与英文版ISO下载及Key激活码
Windows Server 2008 R2 MSDN ISO镜像简体中文版 文件名:cn_windows_server_2008_r2_standard_enterprise_datacenter_ ...
- Python Web开发之路
Flask相关 1.DBUtils数据库连接池 2.Flask之初体验 3.Flask之WTForms 4.Flask之信号 5.Flask之flask-session 6.Flask之flask-s ...
- oauth2(转载http://www.rollosay.com/it/%E4%BD%BF%E7%94%A8OAuth-Server-PHP%E5%AE%9E%E7%8E%B0OAuth2%E6%9C%8D%E5%8A%A1)
http://www.rollosay.com/it/%E4%BD%BF%E7%94%A8OAuth-Server-PHP%E5%AE%9E%E7%8E%B0OAuth2%E6%9C%8D%E5%8A ...
- http之url和uri
HTTP使用统一资源标识符(Uniform Resource Identifiers, URI)来传输数据和建立连接.URL是一种特殊类型的URI,包含了用于查找某个资源的足够的信息 URL,全称是U ...
- 20155316 2016-2017-2 《Java程序设计》第8周学习总结
教材学习内容总结 课堂部分要点 数据结构与算法 与 Java相结合 collection API:数据结构 crypt:密码学 操作系统 考试部分重点 实验楼:Linux第四节 教材:第6章.第14章 ...
- php+mysql事务处理例子详细分析实例
一.数据引擎innodb用begin,rollback,commit来实现提交事务处理,begin开始事务后出现错误就rollback事务回滚或者没有错误就commit提事务提交确认完成. start ...
- LINUX实践--程序破解
实验思想 本次实验的主要思想有两个,第一个是修改跳转指令,把它变成无条件跳转使得无论输入什么用户名都跳转到失败的那个选项中去,第二个思想是修改比对的内容,即不判断条件,从而成功 实验步骤 1.首先从老 ...