Java 同步代码块 - Synchronized Blocks
java锁实现原理:
http://blog.csdn.net/endlu/article/details/51249156
The synchronized
keyword can be used to mark four different types of blocks:
- Instance methods
- Static methods
- Code blocks inside instance methods
- Code blocks inside static methods
Instance methods & Code blocks inside instance methods
Java实例方法同步是同步在拥有该方法的对象上
同步构造器中用括号括起来的对象叫做监视器对象
public class SyncBlockTest { public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(2);
final MySyncBlockClass syncBlockClass = new MySyncBlockClass();
es.submit(new Runnable() {
@Override
public void run() {
try {
syncBlockClass.mehtod1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
es.submit(new Runnable() {
@Override
public void run() {
try {
syncBlockClass.mehtod2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
es.shutdown();
} } class MySyncBlockClass { public synchronized void mehtod1() throws InterruptedException {
TimeUnit.SECONDS.sleep(1);
System.out.println(System.currentTimeMillis() + ":method1 run.");
} public synchronized void mehtod2() throws InterruptedException {
TimeUnit.SECONDS.sleep(4);
System.out.println(System.currentTimeMillis() + ":method2 run.");
}
} // method1较method2延迟了2000ms
// 1479350064132:method2 run.
// 1479350066132:method1 run.
实例方法同步
/**
* method1 与method2等效
* 同步构造器中用括号括起来的对象叫做监视器对象
*
* @throws InterruptedException
*/
public synchronized void mehtod1() throws InterruptedException {
TimeUnit.SECONDS.sleep(1);
System.out.println(System.currentTimeMillis() + ":method1 run.");
} public synchronized void mehtod2() throws InterruptedException {
synchronized (this) {
TimeUnit.SECONDS.sleep(4);
System.out.println(System.currentTimeMillis() + ":method2 run.");
}
}
实例方法中的同步块
Static methods & Code blocks inside static methods
静态方法的同步是指同步在该方法所在的类对象上。因为在Java虚拟机中一个类只能对应一个类对象,所以同时只允许一个线程执行同一个类中的静态同步方法。
public class SyncBlockTest { public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(2);
final MySyncBlockClass syncBlockClass1 = new MySyncBlockClass();
final MySyncBlockClass syncBlockClass2 = new MySyncBlockClass();
es.submit(new Runnable() {
@Override
public void run() {
try {
syncBlockClass1.mehtod1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
es.submit(new Runnable() {
@Override
public void run() {
try {
syncBlockClass2.mehtod2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
es.shutdown();
} } class MySyncBlockClass { public static synchronized void mehtod1() throws InterruptedException {
TimeUnit.SECONDS.sleep(1);
System.out.println(System.currentTimeMillis() + ":method1 run.");
} public static synchronized void mehtod2() throws InterruptedException {
TimeUnit.SECONDS.sleep(4);
System.out.println(System.currentTimeMillis() + ":method2 run.");
}
} // method1较method2延迟了3000ms
// 1479358310630:method1 run.
// 1479358314631:method2 run.
静态方法同步
/**
* method1 与method2等效
* 静态方法中的同步块
*
* @throws InterruptedException
*/
public static synchronized void mehtod1() throws InterruptedException {
TimeUnit.SECONDS.sleep(1);
System.out.println(System.currentTimeMillis() + ":method1 run.");
} public static synchronized void mehtod2() throws InterruptedException {
synchronized (MySyncBlockClass.class) {
TimeUnit.SECONDS.sleep(4);
System.out.println(System.currentTimeMillis() + ":method2 run.");
}
}
静态方法中的同步块
示例:
以下代码对应的Block关系如下:
synchronized(class)与 static synchronized 等效
public class SyncMethod2 {
private int value = 0;
private final Object mutex = new Object(); public synchronized int incAndGet0() {
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("static synchronized void incAndGet0");
return ++value;
} public int incAndGet1() {
synchronized(this){
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("static synchronized void incAndGet1");
return ++value;
}
} public int incAndGet2() {
synchronized(SyncMethod.class){
++value;
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("static synchronized void incAndGet4");
}
return 0;
} public int incAndGet3() {
synchronized(mutex){
return ++value;
}
} public static synchronized void incAndGet4() {
try {
TimeUnit.SECONDS.sleep(4);
System.out.println("static synchronized void incAndGet4");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
各种同步场景
Java 同步代码块 - Synchronized Blocks的更多相关文章
- java多线层同时运行的解决,同步代码块synchronized
/* 多个线层同时操作一个数据 会导制数据超出 同步代码块 synchronized(对像) { 需要同步的代码 } */ class Do7 { public static void main(St ...
- java 同步代码块与同步方法
同步代码块 synchronized (obj) { // 代码块 } obj 为同步监视器,以上代码的含义为:线程开始执行同步代码块(中的代码)之前,必须先获得对同步监视器的锁定. 代码块中的代码是 ...
- java 多线程:线程通信-等待通知机制wait和notify方法;(同步代码块synchronized和while循环相互嵌套的差异);管道通信:PipedInputStream;PipedOutputStream;PipedWriter; PipedReader
1.等待通知机制: 等待通知机制的原理和厨师与服务员的关系很相似: 1,厨师做完一道菜的时间不确定,所以厨师将菜品放到"菜品传递台"上的时间不确定 2,服务员什么时候可以取到菜,必 ...
- 彻底理解线程同步与同步代码块synchronized
public class Demo { public static synchronized void fun1(){ } public synchronized void fun2(){ } pub ...
- 36. 解决线程问题方式一(同步代码块synchronized)
解决线程问题: 方式一:同步代码块(synchronized) 语法: synchronized ("锁对象") { //需要锁定的代码 } ...
- JAVA之旅(十三)——线程的安全性,synchronized关键字,多线程同步代码块,同步函数,同步函数的锁是this
JAVA之旅(十三)--线程的安全性,synchronized关键字,多线程同步代码块,同步函数,同步函数的锁是this 我们继续上个篇幅接着讲线程的知识点 一.线程的安全性 当我们开启四个窗口(线程 ...
- Java基础8-多线程;同步代码块
作业解析 利用白富美接口案例,土豪征婚使用匿名内部类对象实现. interface White{ public void white(); } interface Rich{ public void ...
- Java之同步代码块处理实现Runnable的线程安全问题
/** * 例子:创建三个窗口卖票,总票数为100张.使用实现Runnable接口的方式 * * 1.问题:卖票过程中,出现了重票.错票 -->出现了线程的安全问题 * 2.问题出现的原因:当某 ...
- Java 基础 线程的Runnable接口 /线程的同步方法 /同步代码块
笔记: /**通过 Runnable接口来实现多线程 * 1. 创建一个实现runnable 接口的类 * 2. 在类中实现接口的run() 抽象方法 * 3. 创建一个runnable 接口实现类的 ...
随机推荐
- [BZOJ4408][Fjoi 2016]神秘数
[BZOJ4408][Fjoi 2016]神秘数 试题描述 一个可重复数字集合S的神秘数定义为最小的不能被S的子集的和表示的正整数.例如S={1,1,1,4,13},1 = 12 = 1+13 = 1 ...
- SharePreferences的DB实现
存储一些简单数据的时候,最快的实现是用SharePreferences,但SharePreferences的可靠性不高,在某些非官方ROM上,总是存取失败.后来想到用数据库来存取.产品中,存取的数据项 ...
- Windows10+Ubuntu双系统安装 (转)
1.Windows10+Ubuntu双系统安装: http://www.jianshu.com/p/2eebd6ad284d 2.UEFI启动模式安装ubuntu指南 : http://col ...
- JavaScript高级程序设计学习笔记--高级技巧
惰性载入函数 因为浏览器之间行为的差异,多数JavaScript代码包含了大量的if语句,将执行引导到正确的代码中,看看下面来自上一章的createXHR()函数. function createXH ...
- 启动Tomcat报异常host-manager does not exist or is not a readable directory
前几天重新安装了Tomcat6,安装完Tomcat6后在wepapps下面会有一些tomcat自带的项目(root.manager.host- manager等几个),这几天项目没什么用我就删掉了,后 ...
- 转:Autodesk 2017软件下载+注册机+破解方法(持续更新)
转载自http://blog.sina.com.cn/s/blog_710225790102w03e.html Autodesk 2017安装步骤: 安装Autodesk 2017相关软件 使用序列号 ...
- [Android Pro] PullToRefreshListView怎么设置各个item之间的间距
reference to : http://blog.csdn.net/qq_25943493/article/details/50923895 要设置第三方的上拉下载listView的item之间 ...
- ASP.NET知识总结(4.请求管道中的19个事件)
(1)BeginRequest: 开始处理请求 (2)AuthenticateRequest授权验证请求,获取用户授权信息 (3):PostAuthenticateRequest获取成功 (4): A ...
- Hadoop 大数据第一天
大数据第一天 1.Hadoop生态系统 1.1 Hadoop v1.0 架构 MapReduce(用于数据计算) HDFS(用于存储数据) 1.2 Hadoop v2.0 架构 MapReduce(用 ...
- .NET 农码一生
农码一生博文索引 http://www.cnblogs.com/zhaopei/p/Indexes.html 那些年搞不懂的术语.概念:协变.逆变.不变体 http://www.cnblogs.com ...