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 接口实现类的 ...
随机推荐
- YII2 日志
YII 提供的日志写入方法: Yii::getLogger()->log($message, $level, $category = 'application') Yii::trace($mes ...
- ecplise 常用快捷键
/* * alt+/ * * A:main * main+alt+/ * B:输出语句 * syso+alt+/ * C:提示作用 * * */ /* * 常用快捷键 * 1.格式化:ctrl+shi ...
- Angular2 架构
1. 说明 Angular 2 是一个用 HTML 和 JavaScript (或者可以编译成JavaScript)来构建应用程序的框架.该框架包含了一系列的库. 在 Angular 里,我们这样 ...
- Python:Pycharm下无法导入安装好的第三方模块?
Pycharm下无法导入安装好的第三方模块requests? 在cmd下使用pip安装好requests模块后,可以使用import requests,但在Pycharm IDE下无法导入,出现如下错 ...
- vim技巧
(三)多窗口操作 改变高度:res +n(增加n行的高度)n ctrlw +/-改变宽度:vertical res +n(增加n列的宽度)n ctrl w >/< (一)缩进 vim提供 ...
- go:系统参数or函数--未完
系统参数: os.Args 存放命令参数的字符串数组,其中os.Arg[0]为命令本身的路径,其余项存放输入的参数 例:$ go run myapp.exe -d /home os.Args[0]: ...
- DataTable select根据条件取值
1.封装独立方法 // 执行DataTable中的查询返回新的DataTable /// </summary> /// <param name="dt">源 ...
- October 20th Week 43rd Thursday, 2016
Now, it's clear. OPPO R9s 这一刻 更清晰. I want a new mobile phone, because the one I am using is broken. ...
- 【控制iOS7兼容iOS6 状态栏的显示不完全 简单缩写】
#if ios7 self.automaticallyAdjustsScrollViewInsets = YES; self.edgesForExtendedLayout = UIRectEdgeNo ...
- Android Telephony —— 手机信号实时变化源码分析过程记录
源码版本:4.4 跳过InCallActivity等UI实现.先看service以及底层. 1, 在frameworks/opt下面会发现如下文件列表: ./telephony/src/java/co ...