java锁实现原理:

http://blog.csdn.net/endlu/article/details/51249156

The synchronized keyword can be used to mark four different types of blocks:

  1. Instance methods
  2. Static methods
  3. Code blocks inside instance methods
  4. 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的更多相关文章

  1. java多线层同时运行的解决,同步代码块synchronized

    /* 多个线层同时操作一个数据 会导制数据超出 同步代码块 synchronized(对像) { 需要同步的代码 } */ class Do7 { public static void main(St ...

  2. java 同步代码块与同步方法

    同步代码块 synchronized (obj) { // 代码块 } obj 为同步监视器,以上代码的含义为:线程开始执行同步代码块(中的代码)之前,必须先获得对同步监视器的锁定. 代码块中的代码是 ...

  3. java 多线程:线程通信-等待通知机制wait和notify方法;(同步代码块synchronized和while循环相互嵌套的差异);管道通信:PipedInputStream;PipedOutputStream;PipedWriter; PipedReader

    1.等待通知机制: 等待通知机制的原理和厨师与服务员的关系很相似: 1,厨师做完一道菜的时间不确定,所以厨师将菜品放到"菜品传递台"上的时间不确定 2,服务员什么时候可以取到菜,必 ...

  4. 彻底理解线程同步与同步代码块synchronized

    public class Demo { public static synchronized void fun1(){ } public synchronized void fun2(){ } pub ...

  5. 36. 解决线程问题方式一(同步代码块synchronized)

    解决线程问题: 方式一:同步代码块(synchronized) 语法: synchronized ("锁对象") {             //需要锁定的代码       }   ...

  6. JAVA之旅(十三)——线程的安全性,synchronized关键字,多线程同步代码块,同步函数,同步函数的锁是this

    JAVA之旅(十三)--线程的安全性,synchronized关键字,多线程同步代码块,同步函数,同步函数的锁是this 我们继续上个篇幅接着讲线程的知识点 一.线程的安全性 当我们开启四个窗口(线程 ...

  7. Java基础8-多线程;同步代码块

    作业解析 利用白富美接口案例,土豪征婚使用匿名内部类对象实现. interface White{ public void white(); } interface Rich{ public void ...

  8. Java之同步代码块处理实现Runnable的线程安全问题

    /** * 例子:创建三个窗口卖票,总票数为100张.使用实现Runnable接口的方式 * * 1.问题:卖票过程中,出现了重票.错票 -->出现了线程的安全问题 * 2.问题出现的原因:当某 ...

  9. Java 基础 线程的Runnable接口 /线程的同步方法 /同步代码块

    笔记: /**通过 Runnable接口来实现多线程 * 1. 创建一个实现runnable 接口的类 * 2. 在类中实现接口的run() 抽象方法 * 3. 创建一个runnable 接口实现类的 ...

随机推荐

  1. PHP之autoload理解

    举个例子就可以看懂了: 同一目录中有2个文件index.php和test.php,在test.php中定义一个test类. test.php <?php class test{ public f ...

  2. Python自动化之一对多

    一对多 建立一对多关系之后(也就是加了外键),会在字表里面多一个"外键字段_id"这个字段 查询 #_*_coding:utf-8_*_ from django.db import ...

  3. MATLAB的SAVE命令动态批量保存TXT文件

    1.使用save(): for i=1:6 str=[num2str(i),’.txt’]; m=[1 2; 3 4]; save(str,’m’,’-ascii’);%注意m的单引号,一定记得加上, ...

  4. MVC学习笔记

    7 天玩转 ASP.NET MVC 阅读笔记 1.Web Form的问题 1.响应慢,web控件转化成html需要时间 2.带宽消耗,页面保存web控件的状态(viewstate) 3.由web控件生 ...

  5. Effective Python2 读书笔记3

    Item 22: Prefer Helper Classes Over Bookkeeping with Dictionaries and Tuples For example, say you wa ...

  6. [python面向对象]--基础篇

    1.#类 #类就是一个模板,模板里可以包含多个函数,函数里实现一些功能 #定义一个类 class bar: def foo(self,agr): print(self,agr) obj = bar() ...

  7. linux升级openssh

    升级sshd到OpenSSH-6.7并删除老版本ssh 1)升级前准备 查看是否缺包 # rpm -qa | egrep "gcc|make|perl|pam|pam-devel" ...

  8. MySQL源码分析:源码文件结构及主要数据结构

    原文地址:http://blog.itpub.net/30186219/viewspace-1481125/BUILD: 内含在各个平台.各种编译器下进行编译的脚本.如compile-pentium- ...

  9. SQL入门语句之SELECT和WHERE

    一.SQL入门语句之SELECT SELECT语句用于从数据库表中获取数据,结果表的形式返回数据.这些结果表也被称为结果集 1.从数据库表中取部分字段 select 字段A,字段B from tabl ...

  10. 深入理解MVC模式

    一,什么是MVC模式 该模式是一种软件设计典范,他把软件系统划分为三个基本部分:模型层(Model).视图层(View).控制器(Controller) *Model(模型)表示应用程序核心(比如数据 ...