-
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();
}
}
|