- 浏览: 175389 次
- 性别:
- 来自: 苏州
文章分类
- 全部博客 (87)
- Android (7)
- J2EE (34)
- JavaScript (6)
- CSS (1)
- Scala (0)
- WEB (5)
- Ruby (1)
- J2EE Netbeans JDK (1)
- Maven (2)
- AndroidMenuTest (0)
- ExtJS (1)
- MyBatis (4)
- iBatis (3)
- Quartz (1)
- JavaABC (3)
- HTML (1)
- JQuery (2)
- mysql (3)
- Linux (2)
- windows (1)
- ant (2)
- jboss (1)
- eclipse (1)
- junit (1)
- nginx (1)
- Google (0)
- git (2)
- python (1)
- kafka (1)
- sqlserver (1)
- jdk8+ (1)
Java Concurrency / Multithreading Tutorial
并发编程网
Table of Contents
The Java synchronized Keyword
Synchronized Instance Methods
Synchronized Static Methods
Synchronized Blocks in Instance Methods
Synchronized Blocks in Static Methods
Java Synchronized Example
Java Concurrency Utilities
A Java synchronized block marks a method or a block of code as synchronized. Java synchronized blocks can be used to avoid race conditions.
The Java synchronized Keyword
Synchronized blocks in Java are marked with the synchronized keyword. A synchronized block in Java is synchronized on some object. All synchronized blocks synchronized on the same object can only have one thread executing inside them at the same time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.
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
These blocks are synchronized on different objects. Which type of synchronized block you need depends on the concrete situation.
Synchronized Instance Methods
Here is a synchronized instance method:
Notice the use of the synchronized keyword in the method declaration. This tells Java that the method is synchronized.
A synchronized instance method in Java is synchronized on the instance (object) owning the method. Thus, each instance has its synchronized methods synchronized on a different object: the owning instance. Only one thread can execute inside a synchronized instance method. If more than one instance exist, then one thread at a time can execute inside a synchronized instance method per instance. One thread per instance.
Synchronized Static Methods
Static methods are marked as synchronized just like instance methods using the synchronized keyword. Here is a Java synchronized static method example:
Also here the synchronized keyword tells Java that the method is synchronized.
Synchronized static methods are synchronized on the class object of the class the synchronized static method belongs to. Since only one class object exists in the Java VM per class, only one thread can execute inside a static synchronized method in the same class.
If the static synchronized methods are located in different classes, then one thread can execute inside the static synchronized methods of each class. One thread per class regardless of which static synchronized method it calls.
Synchronized Blocks in Instance Methods
You do not have to synchronize a whole method. Sometimes it is preferable to synchronize only part of a method. Java synchronized blocks inside methods makes this possible.
Here is a synchronized block of Java code inside an unsynchronized Java method:
This example uses the Java synchronized block construct to mark a block of code as synchronized. This code will now execute as if it was a synchronized method.
Notice how the Java synchronized block construct takes an object in parentheses. In the example "this" is used, which is the instance the add method is called on. The object taken in the parentheses by the synchronized construct is called a monitor object. The code is said to be synchronized on the monitor object. A synchronized instance method uses the object it belongs to as monitor object.
Only one thread can execute inside a Java code block synchronized on the same monitor object.
The following two examples are both synchronized on the instance they are called on. They are therefore equivalent with respect to synchronization:
Thus only a single thread can execute inside either of the two synchronized blocks in this example.
Had the second synchronized block been synchronized on a different object than this, then one thread at a time had been able to execute inside each method.
Synchronized Blocks in Static Methods
Here are the same two examples as static methods. These methods are synchronized on the class object of the class the methods belong to:
Only one thread can execute inside any of these two methods at the same time.
Had the second synchronized block been synchronized on a different object than MyClass.class, then one thread could execute inside each method at the same time.
Java Synchronized Example
Here is an example that starts 2 threads and have both of them call the add method on the same instance of Counter. Only one thread at a time will be able to call the add method on the same instance, because the method is synchronized on the instance it belongs to.
Two threads are created. The same Counter instance is passed to both of them in their constructor. The Counter.add() method is synchronized on the instance, because the add method is an instance method, and marked as synchronized. Therefore only one of the threads can call the add() method at a time. The other thread will wait until the first thread leaves the add() method, before it can execute the method itself.
If the two threads had referenced two separate Counter instances, there would have been no problems calling the add() methods simultaneously. The calls would have been to different objects, so the methods called would also be synchronized on different objects (the object owning the method). Therefore the calls would not block. Here is how that could look:
Notice how the two threads, threadA and threadB, no longer reference the same counter instance. The add method of counterA and counterB are synchronized on their two owning instances. Calling add() on counterA will thus not block a call to add() on counterB.
Java Concurrency Utilities
The synchronized mechanism was Java's first mechanism for synchronizing access to objects shared by multiple threads. The synchronized mechanism isn't very advanced though. That is why Java 5 got a whole set of concurrency utility classes to help developers implement more fine grained concurrency control than what you get with synchronized
并发编程网
Table of Contents
The Java synchronized Keyword
Synchronized Instance Methods
Synchronized Static Methods
Synchronized Blocks in Instance Methods
Synchronized Blocks in Static Methods
Java Synchronized Example
Java Concurrency Utilities
A Java synchronized block marks a method or a block of code as synchronized. Java synchronized blocks can be used to avoid race conditions.
The Java synchronized Keyword
Synchronized blocks in Java are marked with the synchronized keyword. A synchronized block in Java is synchronized on some object. All synchronized blocks synchronized on the same object can only have one thread executing inside them at the same time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.
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
These blocks are synchronized on different objects. Which type of synchronized block you need depends on the concrete situation.
Synchronized Instance Methods
Here is a synchronized instance method:
public synchronized void add(int value){ this.count += value; }
Notice the use of the synchronized keyword in the method declaration. This tells Java that the method is synchronized.
A synchronized instance method in Java is synchronized on the instance (object) owning the method. Thus, each instance has its synchronized methods synchronized on a different object: the owning instance. Only one thread can execute inside a synchronized instance method. If more than one instance exist, then one thread at a time can execute inside a synchronized instance method per instance. One thread per instance.
Synchronized Static Methods
Static methods are marked as synchronized just like instance methods using the synchronized keyword. Here is a Java synchronized static method example:
public static synchronized void add(int value){ count += value; }
Also here the synchronized keyword tells Java that the method is synchronized.
Synchronized static methods are synchronized on the class object of the class the synchronized static method belongs to. Since only one class object exists in the Java VM per class, only one thread can execute inside a static synchronized method in the same class.
If the static synchronized methods are located in different classes, then one thread can execute inside the static synchronized methods of each class. One thread per class regardless of which static synchronized method it calls.
Synchronized Blocks in Instance Methods
You do not have to synchronize a whole method. Sometimes it is preferable to synchronize only part of a method. Java synchronized blocks inside methods makes this possible.
Here is a synchronized block of Java code inside an unsynchronized Java method:
public void add(int value){ synchronized(this){ this.count += value; } }
This example uses the Java synchronized block construct to mark a block of code as synchronized. This code will now execute as if it was a synchronized method.
Notice how the Java synchronized block construct takes an object in parentheses. In the example "this" is used, which is the instance the add method is called on. The object taken in the parentheses by the synchronized construct is called a monitor object. The code is said to be synchronized on the monitor object. A synchronized instance method uses the object it belongs to as monitor object.
Only one thread can execute inside a Java code block synchronized on the same monitor object.
The following two examples are both synchronized on the instance they are called on. They are therefore equivalent with respect to synchronization:
public class MyClass { public synchronized void log1(String msg1, String msg2){ log.writeln(msg1); log.writeln(msg2); } public void log2(String msg1, String msg2){ synchronized(this){ log.writeln(msg1); log.writeln(msg2); } } }
Thus only a single thread can execute inside either of the two synchronized blocks in this example.
Had the second synchronized block been synchronized on a different object than this, then one thread at a time had been able to execute inside each method.
Synchronized Blocks in Static Methods
Here are the same two examples as static methods. These methods are synchronized on the class object of the class the methods belong to:
public class MyClass { public static synchronized void log1(String msg1, String msg2){ log.writeln(msg1); log.writeln(msg2); } public static void log2(String msg1, String msg2){ synchronized(MyClass.class){ log.writeln(msg1); log.writeln(msg2); } } }
Only one thread can execute inside any of these two methods at the same time.
Had the second synchronized block been synchronized on a different object than MyClass.class, then one thread could execute inside each method at the same time.
Java Synchronized Example
Here is an example that starts 2 threads and have both of them call the add method on the same instance of Counter. Only one thread at a time will be able to call the add method on the same instance, because the method is synchronized on the instance it belongs to.
public class Counter{ long count = 0; public synchronized void add(long value){ this.count += value; } } public class CounterThread extends Thread{ protected Counter counter = null; public CounterThread(Counter counter){ this.counter = counter; } public void run() { for(int i=0; i<10; i++){ counter.add(i); } } } public class Example { public static void main(String[] args){ Counter counter = new Counter(); Thread threadA = new CounterThread(counter); Thread threadB = new CounterThread(counter); threadA.start(); threadB.start(); } }
Two threads are created. The same Counter instance is passed to both of them in their constructor. The Counter.add() method is synchronized on the instance, because the add method is an instance method, and marked as synchronized. Therefore only one of the threads can call the add() method at a time. The other thread will wait until the first thread leaves the add() method, before it can execute the method itself.
If the two threads had referenced two separate Counter instances, there would have been no problems calling the add() methods simultaneously. The calls would have been to different objects, so the methods called would also be synchronized on different objects (the object owning the method). Therefore the calls would not block. Here is how that could look:
public class Example { public static void main(String[] args){ Counter counterA = new Counter(); Counter counterB = new Counter(); Thread threadA = new CounterThread(counterA); Thread threadB = new CounterThread(counterB); threadA.start(); threadB.start(); } }
Notice how the two threads, threadA and threadB, no longer reference the same counter instance. The add method of counterA and counterB are synchronized on their two owning instances. Calling add() on counterA will thus not block a call to add() on counterB.
Java Concurrency Utilities
The synchronized mechanism was Java's first mechanism for synchronizing access to objects shared by multiple threads. The synchronized mechanism isn't very advanced though. That is why Java 5 got a whole set of concurrency utility classes to help developers implement more fine grained concurrency control than what you get with synchronized
发表评论
-
日志过滤小工具
2020-01-06 20:15 4521.从全量日志中截断部 ... -
GC参考手册
2017-11-09 14:12 549英文版原文:GC Tuning: In Practice 垃圾 ... -
IDENTITY_INSERT 设置为 OFF 时无法指定插入自增ID
2017-02-15 16:10 660IDENTITY_INSERT 设置为 OFF 时,无法指定I ... -
运行时Exception:Wrong return type in function
2015-11-17 21:31 1524D:\Soft\jdk1.7.0_79\bin\java ... -
Java中的常量:如何避免反模式
2015-10-20 20:41 449参考http://www.importnew.com/1670 ... -
java Socket通信小栗子
2015-09-14 09:25 614server端: package com.test.soc ... -
MyBatis 自动生成xml文件
2015-03-12 11:22 3799package com.test.mybatis; ... -
Java mail test
2015-02-12 11:03 1304mail局域网Exchange服务器测试代码,仅限发送到dom ... -
Comparison method violates its general contract!
2014-10-22 17:24 959jdk1.6升级到1.7后Comparator有null的参数 ... -
JDK1.7 不兼容compare方法
2014-10-21 16:20 787java.lang.IllegalArgumentExcept ... -
Unknown Source的出现及解决
2014-06-18 10:03 929http://www.2cto.com/kf/201103/8 ... -
ApplicationDeadlockException
2014-06-16 15:39 784参考 : How to avoid huge transact ... -
Java Date相关处理
2014-02-26 14:35 6061.获取UTC时间: Calendar c ... -
Error listenerStart
2013-12-11 19:25 729INFO: Deploying web applicati ... -
Error configuring application listener of class org.springframework.web.context.
2013-12-07 18:54 38181如果Eclipse的BuildPath里面不缺jar包并且在 ... -
iReport字体报错“JRFontNotFoundException”
2013-10-11 11:08 12797net.sf.jasperreports.engine.uti ... -
Eclipse里Jboss的配置
2013-07-15 17:41 9601.\WorkSpace\.metadata\.plugins ... -
Ant安装使用入门
2013-07-04 14:03 569下载Ant之后,增加环境变量1.ANT_HOME=xx/xx/ ... -
javaSystem获取系统信息
2013-03-27 16:30 807public static void main(Strin ... -
设计模式学习笔记
2013-03-22 18:01 839简单工厂,策略模式,单一职责,开放封闭,依赖倒转 装饰模式,代 ...
相关推荐
Java Concurrency in Practice 英文无水印pdf pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者...
《Java并发编程实践》是Java开发者必读的经典之作,由Brian Goetz等多位专家共同撰写。这本书深入浅出地探讨了Java平台上的并发问题,帮助读者理解和掌握如何编写高效、可靠且可维护的多线程应用程序。以下是该书...
<<java并行编程>>英文版chm格式,英文名称<Java Concurrency in Practice>,一直想买这本书,但总是缺货,找到了电子版,分享给大家。 Java Concurrency in Practice By Brian Goetz, Tim Peierls, Joshua Bloch,...
Using the concurrency building blocks in java.util.concurrent Performance optimization dos and don'ts Testing concurrent programs Advanced topics such as atomic variables, nonblocking algorithms, ...
Java Concurrency in practice
Java Concurrency in Practice JAVA并发编程实践中文版(全)第二部分
实践中的Java并发和多线程 这是发行的的代码存储库。 它包含从头到尾完成视频课程所需的所有支持项目文件。 关于视频课程 多核处理器无处不在-从超级计算机到随身携带的移动设备。 这就是为什么现代开发人员必须知道...
《Java Concurrency in Practice》是Java并发编程领域的一本经典著作,由Brian Goetz、Tim Peierls、Joshua Bloch、Joseph Bowles和Doug Lea等专家共同编写。这本书深入探讨了Java平台上的多线程和并发编程,旨在...
java concurrency in practice 经典的多线程编程书籍,英文版
《Java Concurrency In Practice》是一本关于Java并发编程的经典著作,由Brian Göetz、Tim Peierls、Joshua Bloch、Joseph Bowbeer、David Holmes和Doug Lea共同编写。本书深入探讨了Java平台上的多线程编程技巧,...
本笔记将深入探讨《Java Concurrency In Practice》这本书中的核心概念,结合Guava库的实际使用案例,帮助读者理解并掌握Java并发编程的精髓。 首先,我们来了解Java并发的基础知识。Java提供了丰富的并发工具类,...
《Java Concurrency in Practice》是Java并发编程领域的一本经典著作,由Brian Goetz、Tim Peierls、Joshua Bloch、Joe Bowbeer、David Holmes和Doug Lea合著,国内有热心人士进行了中文翻译,使得更多的中国开发者...
首先,"Java Concurrency in Practice"是Java并发编程的经典之作,由Brian Goetz、Tim Peierls、Joshua Bloch、David Holmes和Doug Lea合著。这本书提供了一套实用的指导原则、设计模式和最佳实践,帮助Java开发者...
java_concurrency_in_practice.pdf jcip-examples-src.jar jcip-annotations-src.jar 英文版是高清晰的,实战和实践都是同一帮人对英文版书的翻译,网传实战的翻译质量更好,实战是2012年出版的,应该是对前一版实践...
- **书名**:《Java并发实践》(Java Concurrency in Practice) - **作者**:Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, Doug Lea - **出版社**:Addison Wesley Professional - **...