Java同步块(synchronized block)使用详解
来源:互联网 发布:js正则匹配指定字符串 编辑:程序博客网 时间:2024/06/01 18:48
Java同步关键字(synchronzied)
实例方法同步
静态方法同步
实例方法中同步块
静态方法中同步块
Java同步示例
Java 同步关键字(synchronized)
实例方法
静态方法
实例方法中的同步块
静态方法中的同步块
实例方法同步
1
2
public
synchronized
void
add(
int
value){
this
.count += value;
}
静态方法同步
1
2
3
public
static
synchronized
void
add(
int
value){
count += value;
}
实例方法中的同步块
1
2
3
4
5
public
void
add(
int
value){
synchronized
(
this
){
this
.count += value;
}
}
1
2
3
4
5
6
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);
}
}
}
静态方法中的同步块
1
2
3
4
5
6
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);
}
}
}
Java同步实例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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();
}
}
1
2
3
4
5
6
7
8
9
10
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();
}
}
0 0
- Java同步块(synchronized block)使用详解
- Java Synchronized Blocks(java同步块)
- Java 同步块(synchronized)详细说明
- Synchronized (同步) block使用实例
- java 同步(synchronized)详解
- 使用synchronized块同步方法..
- 使用Synchronized块同步方法
- 使用Synchronized块同步变量
- 使用Synchronized块同步方法
- 使用Synchronized块同步方法
- 使用Synchronized块同步变量
- JAVA 同步代码块synchronized
- java synchronized(同步代码块)
- 初学Java多线程:使用Synchronized块同步变量
- 初学Java多线程:使用Synchronized块同步方法
- 初学Java多线程:使用Synchronized块同步变量
- 十、初学Java多线程:使用Synchronized块同步方法
- 十一、初学Java多线程:使用Synchronized块同步变量
- 十八、UI-Grid 大数据集
- 【第一个爬虫】python爬取58同城企业信息并插入数据库
- 实现ATM取款机功能
- 选拔赛之 线段树
- httpd常见状态码
- Java同步块(synchronized block)使用详解
- 实例记录
- android java substring
- linq表连接遇到的问题
- VMWare 无法联网的配置
- android-architecture学习——todo‑mvp
- Mysql跨表更新 多表update sql语句总结
- construct2在ios下播放声音
- Java版本历史和特性介绍