- 浏览: 178505 次
- 性别:
- 来自: 苏州
-
文章分类
- 全部博客 (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 5041.从全量日志中截断部 ... -
GC参考手册
2017-11-09 14:12 652英文版原文:GC Tuning: In Practice 垃圾 ... -
IDENTITY_INSERT 设置为 OFF 时无法指定插入自增ID
2017-02-15 16:10 694IDENTITY_INSERT 设置为 OFF 时,无法指定I ... -
运行时Exception:Wrong return type in function
2015-11-17 21:31 1570D:\Soft\jdk1.7.0_79\bin\java ... -
Java中的常量:如何避免反模式
2015-10-20 20:41 476参考http://www.importnew.com/1670 ... -
java Socket通信小栗子
2015-09-14 09:25 640server端: package com.test.soc ... -
MyBatis 自动生成xml文件
2015-03-12 11:22 3843package com.test.mybatis; ... -
Java mail test
2015-02-12 11:03 1392mail局域网Exchange服务器测试代码,仅限发送到dom ... -
Comparison method violates its general contract!
2014-10-22 17:24 1007jdk1.6升级到1.7后Comparator有null的参数 ... -
JDK1.7 不兼容compare方法
2014-10-21 16:20 820java.lang.IllegalArgumentExcept ... -
Unknown Source的出现及解决
2014-06-18 10:03 949http://www.2cto.com/kf/201103/8 ... -
ApplicationDeadlockException
2014-06-16 15:39 805参考 : How to avoid huge transact ... -
Java Date相关处理
2014-02-26 14:35 6261.获取UTC时间: Calendar c ... -
Error listenerStart
2013-12-11 19:25 756INFO: Deploying web applicati ... -
Error configuring application listener of class org.springframework.web.context.
2013-12-07 18:54 38235如果Eclipse的BuildPath里面不缺jar包并且在 ... -
iReport字体报错“JRFontNotFoundException”
2013-10-11 11:08 12857net.sf.jasperreports.engine.uti ... -
Eclipse里Jboss的配置
2013-07-15 17:41 9881.\WorkSpace\.metadata\.plugins ... -
Ant安装使用入门
2013-07-04 14:03 590下载Ant之后,增加环境变量1.ANT_HOME=xx/xx/ ... -
javaSystem获取系统信息
2013-03-27 16:30 832public static void main(Strin ... -
设计模式学习笔记
2013-03-22 18:01 865简单工厂,策略模式,单一职责,开放封闭,依赖倒转 装饰模式,代 ...
相关推荐
Fully updated for the new Java SE 6 platform, this no-nonsense tutorial and reliable reference illuminates the most important language and library features with thoroughly tested real-world examples....
12. **Concurrency & Multithreading** (并发与多线程) Shiro 考虑到了多线程环境下的安全问题,提供了一套处理并发和多线程场景的机制。 13. **Testing** (测试) 为方便测试,Shiro 提供了测试支持,允许开发者...
The C++ Standard Library A Tutorial and Reference (2nd Edition)+cppstdlib-code.zip C++标准库(第二版)英文版.pdf 非扫描版+源代码 Prefaceto the SecondEdition xxiii Acknowledgments for the Second...
Chapter 7: Async IO – Multithreading without Threads Chapter 8: Metaclasses – Making Classes (Not Instances) Smarter Chapter 9: Documentation – How to Use Sphinx and reStructuredText Chapter 10: ...
Python参考手册,官方正式版参考手册,chm版。以下摘取部分内容:Navigation index modules | next | Python » 3.6.5 Documentation » Python Documentation contents What’s New in Python ...